<?php
class Payment extends AppModel
{
    var $useTable = false;
    function __construct($id = false, $table = null, $ds = null)
    {
        parent::__construct($id, $table, $ds);
    }
    function CustomizePaymentPage($payKey)
    {
        $PaypalPlatform = $this->_getPaypalPlatformObject();
        $options['headerImageUrl'] = Router::url('/', true) . 'img/logo.png';
        $options['businessName'] = Configure::read('site.name');
        $PaypalPlatform->CallSetPaymentOptions($payKey, $options);
    }
    function getBalance()
    {
        $PaypalPlatform = $this->_getPaypalPlatformObject();
        $resArray = $this->PaypalPlatform->CallGetBalance();
        $ack = strtoupper($resArray["ACK"]);
        $return = 0;
        if ($ack == "SUCCESS") {
            foreach($resArray as $k => $v) {
                if (strtoupper($v) == strtoupper(Configure::read('site.currency_code'))) {
                    $pos = strpos($k, 'L_CURRENCYCODE');
                }
            }
            $return = $resArray['L_AMT' . $pos];
        }
        return $return;
    }
    function processProjectPayment($project_id)
    {
        $this->_saveIPNLog();
        App::import('Model', 'Project');
        $this->Project = new Project();
        $project = $this->Project->find('first', array(
            'conditions' => array(
                'Project.id = ' => $project_id,
            ) ,
            'contain' => array(
                'User',
                'ProjectCategory',
            ) ,
            'recursive' => 1,
        ));
        $transaction_data = $this->Project->User->Transaction->find('first', array('conditions' => array('Transaction.foreign_id' => $project_id, 'Transaction.class' => 'Project', 'Transaction.transaction_type_id' => 3), 'recursive' => -1));

        if (empty($project)) {
            $this->cakeError('error404');
        }
        $paymentDetails = $this->getPaymentDetails($project['Project']['pay_key']);
        App::import('Model', 'AdaptiveTransactionLog');
            $this->AdaptiveTransactionLog = new AdaptiveTransactionLog();
            $previous_log = $this->AdaptiveTransactionLog->find('first', array(
            'conditions' => array(
                'AdaptiveTransactionLog.transaction_id' => $paymentDetails['paymentInfoList.paymentInfo(0).transactionId'],
            ) ,
            'recursive' => -1,
            ));
            
        $this->log('Previous');
        $this->log($previous_log);
         if(empty($previous_log))
            {
            $this->log("Entered");
        if (empty($transaction_data) and $paymentDetails['status'] == 'COMPLETED' && $project['Project']['project_status_id'] == ConstProjectStatus::Pending) {
            $data['Transaction']['foreign_id'] = $project['Project']['id'];
            $data['Transaction']['class'] = 'Project';
            $data['Transaction']['user_id'] = $project['Project']['user_id'];
            $data['Transaction']['amount'] = $paymentDetails['paymentInfoList.paymentInfo(0).receiver.amount'];
            $data['Transaction']['payment_gateway_id'] = ConstPaymentGateways::PayPal;
            $data['Transaction']['transaction_type_id'] = ConstTransactionTypes::Project;
            $this->Project->User->Transaction->create();
            $this->Project->Transaction->save($data);

            $admin_data['Transaction']['foreign_id'] = $project['Project']['id'];
            $admin_data['Transaction']['class'] = 'Project';
            $admin_data['Transaction']['user_id'] = ConstUserIds::Admin;
            $admin_data['Transaction']['amount'] = $paymentDetails['paymentInfoList.paymentInfo(0).receiver.amount'];
            $admin_data['Transaction']['payment_gateway_id'] = ConstPaymentGateways::PayPal;
            $admin_data['Transaction']['transaction_type_id'] = ConstTransactionTypes::Project;
            $this->Project->User->Transaction->create();
            $this->Project->Transaction->save($admin_data);
            
                if (Configure::read('Project.is_auto_approve')) {
                    $_Data['Project']['is_active'] = 1;
					if (!Configure::read('Project.is_enable_idea')) {
						$_Data['Project']['project_funding_start_date'] = date('Y-m-d');
					}
                }
                if(Configure::read('Project.is_auto_approve')){
				if (Configure::read('Project.is_enable_idea')) {
					$_Data['Project']['project_status_id'] = ConstProjectStatus::OpenForIdea;
				} else {
					$_Data['Project']['project_status_id'] = ConstProjectStatus::OpenForFunding;
				}
				}
                $_Data['Project']['id'] = $project['Project']['id'];
                $_Data['Project']['user_id'] = $project['Project']['user_id'];
                $_Data['Project']['name'] = $project['Project']['name'];
                $_Data['Project']['fee_amount'] = $data['Transaction']['amount'];
                $_Data['Project']['action'] = 'add';
                $this->Project->save($_Data);
				$this->Project->_sendAlertOnProjectAdd($project, 'New Project');
          }
        }
        $this->_savePaidLog($project_id, $paymentDetails, 'Project', 1);
    }
    function processUserOrder($data)
    {
        App::import('Model', 'User');
        $this->User = new User();
        App::import('Model', 'UserAddWalletAmount');
        $this->UserAddWalletAmount = new UserAddWalletAmount();
        switch ($data['type']) {
            case 'user':
                $user = $this->User->find('first', array(
                    'conditions' => array(
                        'User.id = ' => $data['user_id']
                    ) ,
                    'contain' => array(
                        'UserPaypalConnection'
                    ) ,
                    'recursive' => 1
                ));
                if (empty($user)) {
                    throw new NotFoundException(__l('Invalid request'));
                }
                if (!empty($data['add_to_wallet_id'])) {
                    $UserAddWalletAmount['id'] = $data['add_to_wallet_id'];
                } else {
                    $this->UserAddWalletAmount->create();
                }
                $UserAddWalletAmount['user_id'] = $data['user_id'];
                $UserAddWalletAmount['amount'] = $data['amount'];
                $UserAddWalletAmount['payment_gateway_id'] = ConstPaymentGateways::PayPal;
                $this->UserAddWalletAmount->create();
                $this->UserAddWalletAmount->save($UserAddWalletAmount, false);
                $add_to_wallet_id = $this->UserAddWalletAmount->id;
                break;
        }
        App::import('Vendor', 'adaptive_paypal/paypal_platform');
        $this->PaypalPlatform = new PaypalPlatform();
        $payment_gateway_id = ConstPaymentGateways::PayPal;
        $paymentGateway = $this->User->Transaction->PaymentGateway->find('first', array(
            'conditions' => array(
                'PaymentGateway.id' => $payment_gateway_id,
            ) ,
            'contain' => array(
                'PaymentGatewaySetting' => array(
                    'fields' => array(
                        'PaymentGatewaySetting.key',
                        'PaymentGatewaySetting.test_mode_value',
                        'PaymentGatewaySetting.live_mode_value',
                    ) ,
                ) ,
            ) ,
            'recursive' => 1
        ));
        if (!empty($paymentGateway['PaymentGatewaySetting'])) {
            foreach($paymentGateway['PaymentGatewaySetting'] as $paymentGatewaySetting) {
                $gateway_settings_options[$paymentGatewaySetting['key']] = $paymentGateway['PaymentGateway']['is_test_mode'] ? $paymentGatewaySetting['test_mode_value'] : $paymentGatewaySetting['live_mode_value'];
            }
        }
        $gateway_settings_options['is_test_mode'] = $paymentGateway['PaymentGateway']['is_test_mode'];
        $this->PaypalPlatform->settings($gateway_settings_options);
        // Request specific required fields
        $actionType = "PAY";
        $cancelUrl = Router::url(array(
            'controller' => 'payments',
            'action' => 'cancel_order',
            $data['type'],
            $add_to_wallet_id,
            'admin' => false
        ) , true);
        $returnUrl = Router::url(array(
            'controller' => 'payments',
            'action' => 'success_order',
            $data['type'],
            $add_to_wallet_id,
            'admin' => false
        ) , true);
        $ipnNotificationUrl = Router::url(array(
            'controller' => 'payments',
            'action' => 'processpayment',
            $data['type'],
            $add_to_wallet_id,
            'admin' => false
        ) , true);
        $currencyCode = Configure::read('site.currency_code');
        $receiverEmailArray = array(
            $gateway_settings_options['payee_account']
        );
        $receiverAmountArray = array(
            $data['amount']
        );
        $receiverPrimaryArray = array();
        $receiverInvoiceIdArray = array(
            md5('addtowallet_' . date('YmdHis'))
        );
        $senderEmail = '';
        //$feesPayer = 'EACHRECEIVER';
        //        $feesPayer = 'SENDER';
        $feesPayer = 'SENDER';
        if (Configure::read('User.signup_fee_payeer') == 'Site') {
            $feesPayer = 'EACHRECEIVER';
        }
        $memo = '';
        $pin = '';
        $preapprovalKey = '';
        $reverseAllParallelPaymentsOnError = '';
        $trackingId = $this->PaypalPlatform->generateTrackingID();
        if (!empty($data['user_paypal_connection_id'])) {
            $userPaypalConnection = $this->User->UserPaypalConnection->find('first', array(
                'conditions' => array(
                    'UserPaypalConnection.id' => $data['user_paypal_connection_id']
                ) ,
                'recursive' => -1
            ));
            $preapprovalKey = trim($userPaypalConnection['UserPaypalConnection']['pre_approval_key']);
            $senderEmail = trim($userPaypalConnection['UserPaypalConnection']['sender_email']);
            $UserAddWalletAmount['user_paypal_connection_id'] = $userPaypalConnection['UserPaypalConnection']['id'];
        }
        // Make the Pay API call
        $resArray = $this->PaypalPlatform->CallPay($actionType, $cancelUrl, $returnUrl, $currencyCode, $receiverEmailArray, $receiverAmountArray, $receiverPrimaryArray, $receiverInvoiceIdArray, $feesPayer, $ipnNotificationUrl, $memo, $pin, $preapprovalKey, $reverseAllParallelPaymentsOnError, $senderEmail, $trackingId);
        $ack = strtoupper($resArray["responseEnvelope.ack"]);
        $return['error'] = 0;
        if ($ack == "SUCCESS") {
            //Update payKey value to user add wallet amount table.
            $update_userwallet = $this->UserAddWalletAmount->updateAll(array(
                'UserAddWalletAmount.pay_key' => "'" . $resArray["payKey"] . "'",
            ) , array(
                'UserAddWalletAmount.id' => $add_to_wallet_id,
            ));
            if ('' == $preapprovalKey) {
                $this->CustomizePaymentPage($resArray["payKey"]);
                $cmd = "cmd=_ap-payment&paykey=" . urldecode($resArray["payKey"]);
                $embedded = false;
                if (Configure::read('paypal.is_embedded_payment_enabled')) {
                    $embedded = true;
                }
                $this->PaypalPlatform->RedirectToPayPal($cmd, $embedded);
                exit;
            } else {
                $payKey = urldecode($resArray["payKey"]);
                $paymentExecStatus = urldecode($resArray["paymentExecStatus"]);
            }
            switch ($data['type']) {
                case 'user':
                    $UserAddWalletAmount['id'] = $add_to_wallet_id;
                    $UserAddWalletAmount['pay_key'] = $resArray["payKey"];
                    $this->UserAddWalletAmount->save($UserAddWalletAmount, false);
                    break;
            }
        } else {
            $ErrorCode = urldecode($resArray["error(0).errorId"]);
            $ErrorMsg = urldecode($resArray["error(0).message"]);
            $ErrorDomain = urldecode($resArray["error(0).domain"]);
            $ErrorSeverity = urldecode($resArray["error(0).severity"]);
            $ErrorCategory = urldecode($resArray["error(0).category"]);
            $return['error_message'] = $ErrorMsg;
            $return['error'] = 1;
        }
        $return['add_to_wallet_id'] = $add_to_wallet_id;
        return $return;
    }
    function payProject($data)
    {
        App::import('Model', 'Project');
        $this->Project = new Project();
        $return['error'] = 0;
        if (!empty($data['payment_gateway_id']) && $data['payment_gateway_id'] == ConstPaymentGateways::PayPal) {
            App::import('Vendor', 'adaptive_paypal/paypal_platform');
            $this->PaypalPlatform = new PaypalPlatform();
            $payment_gateway_id = $data['payment_gateway_id'];
            $paymentGateway = $this->Project->User->Transaction->PaymentGateway->find('first', array(
                'conditions' => array(
                    'PaymentGateway.id' => $payment_gateway_id,
                ) ,
                'contain' => array(
                    'PaymentGatewaySetting' => array(
                        'fields' => array(
                            'PaymentGatewaySetting.key',
                            'PaymentGatewaySetting.test_mode_value',
                            'PaymentGatewaySetting.live_mode_value',
                        ) ,
                    ) ,
                ) ,
                'recursive' => 1
            ));
            if (!empty($paymentGateway['PaymentGatewaySetting'])) {
                foreach($paymentGateway['PaymentGatewaySetting'] as $paymentGatewaySetting) {
                    $gateway_settings_options[$paymentGatewaySetting['key']] = $paymentGateway['PaymentGateway']['is_test_mode'] ? $paymentGatewaySetting['test_mode_value'] : $paymentGatewaySetting['live_mode_value'];
                }
            }
            $gateway_settings_options['is_test_mode'] = $paymentGateway['PaymentGateway']['is_test_mode'];
            $this->PaypalPlatform->settings($gateway_settings_options);
            $project_id = $data['project_id'];
            // Request specific required fields
            $actionType = "PAY";
            $cancelUrl = Router::url('/', true) . 'payments/cancel_projectpayment/' . $project_id;
            $returnUrl = Router::url('/', true) . 'payments/success_projectpayment/' . $project_id;
            $ipnNotificationUrl = Router::url('/', true) . 'payments/processprojectpayment/' . $project_id;
            $currencyCode = Configure::read('site.currency_code');
            $receiverEmailArray = array(
                $gateway_settings_options['payee_account']
            );
            $receiverAmountArray = array(
                $data['amount']
            );
            $receiverPrimaryArray = array();
            $receiverInvoiceIdArray = array(
                md5('ProjectPay_' . date('YmdHis'))
            );
            $senderEmail = '';
            $feesPayer = 'EACHRECEIVER';
            if (Configure::read('Project.project_fee_payeer') == ConstProjectPaymentGatewayFee::Buyer) {
                $feesPayer = 'SENDER';
            }
            $memo = '';
            $pin = '';
            $preapprovalKey = '';
            $reverseAllParallelPaymentsOnError = '';
            $trackingId = $this->PaypalPlatform->generateTrackingID();
            // Make the Pay API call
            $resArray = $this->PaypalPlatform->CallPay($actionType, $cancelUrl, $returnUrl, $currencyCode, $receiverEmailArray, $receiverAmountArray, $receiverPrimaryArray, $receiverInvoiceIdArray, $feesPayer, $ipnNotificationUrl, $memo, $pin, $preapprovalKey, $reverseAllParallelPaymentsOnError, $senderEmail, $trackingId);
            $ack = strtoupper($resArray["responseEnvelope.ack"]);
            $return['error'] = 0;
            if ($ack == "SUCCESS") {
                $this->CustomizePaymentPage($resArray["payKey"]);
                $Projectdata['id'] = $project_id;
                $Projectdata['pay_key'] = $resArray["payKey"];
                $this->Project->Behaviors->detach('Logable');
                $this->Project->save($Projectdata, false);
                $cmd = "cmd=_ap-payment&paykey=" . urldecode($resArray["payKey"]);
                $this->PaypalPlatform->RedirectToPayPal($cmd);
            } else {
                $ErrorMsg = urldecode($resArray["error(0).message"]);
                $return['error_message'] = $ErrorMsg;
                $return['error'] = 1;
            }
        } elseif ($data['payment_gateway_id'] == ConstPaymentGateways::Wallet) {
            $buyer_info = $this->Project->User->find('first', array(
                'conditions' => array(
                    'User.id' => $_SESSION['Auth']['User']['id']
                ) ,
                'fields' => array(
                    'User.id',
                    'User.username',
                    'User.email',
                    'User.available_balance_amount',
                    'User.available_wallet_amount',
                ) ,
                'recursive' => -1
            ));
            // Updating buyer balance //
            $update_buyer_balance = $buyer_info['User']['available_wallet_amount']-$data['amount'];
            $this->Project->User->updateAll(array(
                'User.available_wallet_amount' => "'" . $update_buyer_balance . "'"
            ) , array(
                'User.id' => $_SESSION['Auth']['User']['id']
            ));
            $project = $this->Project->find('first', array(
                'conditions' => array(
                    'Project.id' => $data['project_id']
                ) ,
                'contain' => array(
                    'User',
                    'ProjectCategory',
                ) ,
                'recursive' => 1,
            ));
            
           
            $this->log('Entered');
            $data['Transaction']['foreign_id'] = $project['Project']['id'];
            $data['Transaction']['class'] = 'Project';
            $data['Transaction']['user_id'] = $project['Project']['user_id'];
            $data['Transaction']['amount'] = $data['amount'];
            $data['Transaction']['payment_gateway_id'] = ConstPaymentGateways::Wallet;
            $data['Transaction']['transaction_type_id'] = ConstTransactionTypes::Project;
            $this->Project->User->Transaction->create();
            $transaction_saved = $this->Project->Transaction->save($data);
            $admin_data['Transaction']['foreign_id'] = $project['Project']['id'];
            $admin_data['Transaction']['class'] = 'Project';
            $admin_data['Transaction']['user_id'] = ConstUserIds::Admin;
            $admin_data['Transaction']['amount'] = $data['amount'];
            $admin_data['Transaction']['payment_gateway_id'] = ConstPaymentGateways::Wallet;
            $admin_data['Transaction']['transaction_type_id'] = ConstTransactionTypes::Project;
            $this->Project->User->Transaction->create();
            $transaction_saved = $this->Project->Transaction->save($admin_data);
            if ($transaction_saved) {
                if (Configure::read('Project.is_auto_approve')) {
                    $_Data['Project']['is_active'] = 1;
                    if (Configure::read('Project.is_enable_idea')) {
                        $_Data['Project']['project_status_id'] = ConstProjectStatus::OpenForIdea;
                        $this->Project->_sendAlertOnProjectAdd($project, 'New Project');
                    } else {
                        $_Data['Project']['project_status_id'] = ConstProjectStatus::OpenForFunding;
                        $_Data['Project']['project_funding_start_date'] = date('Y-m-d');
                    }
                } else {
                    $this->Project->_sendAlertOnProjectAdd($project, 'New Project');
                }
                $_Data['Project']['id'] = $project['Project']['id'];
                $_Data['Project']['user_id'] = $project['Project']['user_id'];
                $_Data['Project']['name'] = $project['Project']['name'];
                $_Data['Project']['fee_amount'] = $data['Transaction']['amount'];
                $_Data['Project']['action'] = 'add';
                $this->Project->save($_Data);
            }
        }elseif (!empty($data['payment_gateway_id']) && $data['payment_gateway_id'] == ConstPaymentGateways::NganLuong){
        	App::import('Model', 'NganluongGateway');
        	
        	// CALL BY SUBMIT BUTTON            
			ob_start();
			//Khai báo url trả về 
			$returnUrl = Router::url('/', true) . 'payments/return_nganluong_project/';
			//Giá của cả giỏ hàng
			$price = $data['amount'];
			//Mã giỏ hàng 
			$order_code= 'TraiTimTrieuPhu_'.$data['project_id'];
			//Thông tin giao dịch
			$transaction_info= 'TraiTimTrieuPhu';
		    //Khai báo đối tượng của lớp NL_Checkout
			$this->NganluongGateway = new NganluongGateway();
			//Tạo link thanh toán đến nganluong.vn
			$url= $this->NganluongGateway->buildCheckoutUrl($returnUrl, $this->NganluongGateway->receiver, $transaction_info,  $order_code, $price);
		    ob_clean();
		    header('location: '.$url);
		    ob_end_flush();
		    exit();
        }
        return $return;
    }
/*    function processOrder($data)
    {
        App::import('Model', 'Project');
        $this->Project = new Project();
        App::import('Vendor', 'adaptive_paypal/paypal_platform');
        $this->PaypalPlatform = new PaypalPlatform();
        $payment_gateway_id = ConstPaymentGateways::PayPal;
        if (!empty($data['payment_gateway_id'])) {
            $payment_gateway_id = $data['payment_gateway_id'];
        }
        $paymentGateway = $this->Project->User->Transaction->PaymentGateway->find('first', array(
            'conditions' => array(
                'PaymentGateway.id' => $payment_gateway_id,
            ) ,
            'contain' => array(
                'PaymentGatewaySetting' => array(
                    'fields' => array(
                        'PaymentGatewaySetting.key',
                        'PaymentGatewaySetting.test_mode_value',
                        'PaymentGatewaySetting.live_mode_value',
                    ) ,
                ) ,
            ) ,
            'recursive' => 1
        ));
        $projectfund = $this->Project->ProjectFund->find('first', array(
            'conditions' => array(
                'ProjectFund.id' => $data['item_id']
            ) ,
            'contain' => array(
                'Project' => array(
                    'User' => array(
                        'UserProfile' => array()
                    )
                ) ,
            ) ,
            'recursive' => 3
        ));
        if (empty($projectfund)) {
            $this->cakeError('error404');
        }
        $order_id = $data['item_id'];
        $site_fee = round($projectfund['ProjectFund']['amount']*(Configure::read('Project.fund_commission_percentage') /100) , 2);
        $ProjectFund['id'] = $order_id;
        $gateway_fee = 0;
        $total_amount = round($projectfund['ProjectFund']['amount']+$gateway_fee, 2);
        $itemDetail['amount'] = $total_amount;
        // project owner amount
        $itemDetail['seller_amount'] = $total_amount-$site_fee;
        // amount for admin
        $itemDetail['site_amount'] = $site_fee;
        // project owner paypal account
        $itemDetail['seller_paypal_account'] = $projectfund['Project']['User']['UserProfile']['paypal_account'];
        if ($payment_gateway_id == ConstPaymentGateways::PayPal) {
            if (!empty($paymentGateway['PaymentGatewaySetting'])) {
                foreach($paymentGateway['PaymentGatewaySetting'] as $paymentGatewaySetting) {
                    $gateway_settings_options[$paymentGatewaySetting['key']] = $paymentGateway['PaymentGateway']['is_test_mode'] ? $paymentGatewaySetting['test_mode_value'] : $paymentGatewaySetting['live_mode_value'];
                }
            }
            $gateway_settings_options['is_test_mode'] = $paymentGateway['PaymentGateway']['is_test_mode'];
            $this->PaypalPlatform->settings($gateway_settings_options);
            // Request specific required fields
            if (!empty($projectfund['ProjectFund']['is_delayed_chained_payment'])) {
                $actionType = "PAY_PRIMARY";
            } else {
                $actionType = "PAY";
            }
            $cancelUrl = Router::url('/', true) . 'payments/cancel_order/project/' . $order_id;
            $returnUrl = Router::url('/', true) . 'payments/success_order/project/' . $order_id;
            $ipnNotificationUrl = Router::url('/', true) . 'payments/processpayment/project/' . $order_id;
            $currencyCode = Configure::read('site.currency_code');
            if (!empty($projectfund['ProjectFund']['is_delayed_chained_payment'])) {
                if (Configure::read('Project.payment_gateway_flow_id') == ConstPaymentGatewayFlow::BuyerSellerSite) {
                    $receiverEmailArray = array(
                        $itemDetail['seller_paypal_account'],
                        $gateway_settings_options['payee_account']
                    );
                    $receiverAmountArray = array(
                        $itemDetail['amount'],
                        $itemDetail['site_amount']
                    );
                } else {
                    $receiverEmailArray = array(
                        $gateway_settings_options['payee_account'],
                        $itemDetail['seller_paypal_account']
                    );
                    $receiverAmountArray = array(
                        $itemDetail['amount'],
                        $itemDetail['seller_amount']
                    );
                }
                $receiverPrimaryArray = array(
                    'true',
                    ''
                );
                $receiverInvoiceIdArray = array(
                    md5('primary_' . date('YmdHis')) ,
                    md5('secondary_' . date('YmdHis'))
                );
                $senderEmail = '';
                $feesPayer = $this->_gatewayFeeSettings();
            } else {
                $receiverEmailArray = array(
                    $gateway_settings_options['payee_account']
                );
                $receiverAmountArray = array(
                    $itemDetail['amount']
                );
                $receiverPrimaryArray = array();
                $receiverInvoiceIdArray = array(
                    md5('pledge_' . date('YmdHis'))
                );
                $senderEmail = '';
                $feesPayer = 'EACHRECEIVER';
            }
            $memo = '';
            $pin = '';
            $preapprovalKey = '';
            $reverseAllParallelPaymentsOnError = '';
            $trackingId = $this->PaypalPlatform->generateTrackingID();
            if (!empty($data['user_paypal_connection_id'])) {
                $userPaypalConnection = $this->Project->User->UserPaypalConnection->find('first', array(
                    'conditions' => array(
                        'UserPaypalConnection.id' => $data['user_paypal_connection_id']
                    ) ,
                    'recursive' => -1
                ));
                $preapprovalKey = trim($userPaypalConnection['UserPaypalConnection']['pre_approval_key']);
                $senderEmail = trim($userPaypalConnection['UserPaypalConnection']['sender_email']);
                $ProjectFund['user_paypal_connection_id'] = $userPaypalConnection['UserPaypalConnection']['id'];
            }
            // Make the Pay API call
            $resArray = $this->PaypalPlatform->CallPay($actionType, $cancelUrl, $returnUrl, $currencyCode, $receiverEmailArray, $receiverAmountArray, $receiverPrimaryArray, $receiverInvoiceIdArray, $feesPayer, $ipnNotificationUrl, $memo, $pin, $preapprovalKey, $reverseAllParallelPaymentsOnError, $senderEmail, $trackingId);
            $ack = strtoupper($resArray["responseEnvelope.ack"]);
            $return['error'] = 0;
            if ($ack == "SUCCESS") {
                $this->CustomizePaymentPage($resArray["payKey"]);
                $this->Project->ProjectFund->Behaviors->detach('Logable');
                $ProjectFund['project_id'] = $projectfund['ProjectFund']['project_id'];
                $ProjectFund['user_id'] = $projectfund['ProjectFund']['user_id'];
                $ProjectFund['pay_key'] = $resArray["payKey"];
                $this->Project->ProjectFund->save($ProjectFund, false);
                if ('' == $preapprovalKey) {
                    $cmd = "cmd=_ap-payment&paykey=" . urldecode($resArray["payKey"]);
                    $this->PaypalPlatform->RedirectToPayPal($cmd);
                } else {
                    $payKey = urldecode($resArray["payKey"]);
                    $paymentExecStatus = urldecode($resArray["paymentExecStatus"]);
                }
            } else {
                $ErrorCode = urldecode($resArray["error(0).errorId"]);
                $ErrorMsg = urldecode($resArray["error(0).message"]);
                $ErrorDomain = urldecode($resArray["error(0).domain"]);
                $ErrorSeverity = urldecode($resArray["error(0).severity"]);
                $ErrorCategory = urldecode($resArray["error(0).category"]);
                $return['error_message'] = $ErrorMsg;
                $return['error'] = 1;
            }
        } else if ($payment_gateway_id == ConstPaymentGateways::Wallet) {
            $this->processOrderPayment($order_id, ConstPaymentGateways::Wallet);
        }
        $return['order_id'] = $order_id;
        return $return;
    }
    function processOrderPayment($order_id, $gateway_id = ConstPaymentGateways::PayPal)
    {
        $this->_saveIPNLog();
        App::import('Model', 'Project');
        $this->Project = new Project();
        App::import('Model', 'EmailTemplate');
        $this->EmailTemplate = new EmailTemplate();
        App::import('Core', 'ComponentCollection');
        $collection = new ComponentCollection();
        App::import('Component', 'OauthConsumer');
        $this->OauthConsumer = new OauthConsumerComponent($collection);
        $projectFund = $this->Project->ProjectFund->find('first', array(
            'conditions' => array(
                'ProjectFund.id' => $order_id
            ) ,
            'contain' => array(
                'User' => array(
                    'fields' => array(
                        'User.id',
                        'User.username',
                        'User.available_wallet_amount',
                        'User.blocked_amount',
                        'User.email',
                        'User.fb_user_id',
                        'User.twitter_access_token',
                        'User.twitter_access_key',
                        'User.fb_access_token',
                        'User.fb_user_id',
                    ) ,
                ) ,
            ) ,
            'recursive' => 2
        ));
        if (empty($projectFund)) {
            $this->cakeError('error404');
        }
        $project_id = $projectFund['ProjectFund']['project_id'];
        $_dataProjectFund['ProjectFund']['id'] = $projectFund['ProjectFund']['id'];
        if ($gateway_id == ConstPaymentGateways::PayPal) {
            $paymentDetails = $this->getPaymentDetails($projectFund['ProjectFund']['pay_key']);
            if ($paymentDetails['status'] == 'INCOMPLETE' || $paymentDetails['status'] == 'COMPLETED') {
                $this->_savePaidLog($order_id, $paymentDetails);
                if ($paymentDetails['paymentInfoList.paymentInfo(0).transactionStatus'] == 'REFUNDED' || !empty($paymentDetails['paymentInfoList.paymentInfo(1).transactionStatus']) && $paymentDetails['paymentInfoList.paymentInfo(1).transactionStatus'] == 'REFUNDED') {
                }
            } else {
                $_dataProjectFund['ProjectFund']['is_failed'] = 1;
            }
        } else if ($gateway_id == ConstPaymentGateways::Wallet) {
            $blocked_user_balance = $projectFund['User']['blocked_amount']+$projectFund['ProjectFund']['amount'];
            $available_user_balance = $projectFund['User']['available_wallet_amount']-$projectFund['ProjectFund']['amount'];
            $this->Project->User->updateAll(array(
                'User.blocked_amount' => "'" . $blocked_user_balance . "'",
                'User.available_wallet_amount' => "'" . $available_user_balance . "'"
            ) , array(
                'User.id' => $projectFund['ProjectFund']['user_id']
            ));
        }
        $projectFundData = $this->Project->ProjectFund->find('first', array(
            'conditions' => array(
                'ProjectFund.id' => $_dataProjectFund['ProjectFund']['id']
            ) ,
            'recursive' => -1
        ));
        if (is_null($projectFundData['ProjectFund']['is_paid'])) {
            $data['Transaction']['user_id'] = $projectFund['ProjectFund']['user_id'];
            $data['Transaction']['foreign_id'] = $projectFund['ProjectFund']['id'];
            $data['Transaction']['class'] = 'ProjectFund';
            $data['Transaction']['amount'] = $projectFund['ProjectFund']['amount'];
            $data['Transaction']['site_commission'] = $projectFund['ProjectFund']['site_fee'];
            $data['Transaction']['payment_gateway_id'] = $gateway_id;
            $data['Transaction']['description'] = 'Payment Success';
            $data['Transaction']['transaction_type_id'] = ConstTransactionTypes::ProjectFunding;
            $this->Project->User->Transaction->log($data);
            $transaction_id = $this->Project->User->Transaction->id;
            $this->Project->ProjectFund->updateAll(array(
                'ProjectFund.is_paid' => '0',
                'ProjectFund.payment_gateway_id' => $gateway_id,
            ) , array(
                'ProjectFund.id' => $_dataProjectFund['ProjectFund']['id']
            ));
            $project = $this->Project->find('first', array(
                'conditions' => array(
                    'Project.id' => $projectFund['ProjectFund']['project_id']
                ) ,
                'contain' => array(
                    'User' => array(
                        'fields' => array(
                            'User.id',
                            'User.username',
                            'User.email'
                        ) ,
                        'ProjectFund' => array(
                            'fields' => array(
                                'ProjectFund.user_id',
                                'ProjectFund.amount'
                            )
                        ) ,
                        'ProjectFollower' => array(
                            'fields' => array(
                                'ProjectFollower.user_id'
                            )
                        ) ,
                    ) ,
                    'Attachment',
                ) ,
                'fields' => array(
                    'Project.collected_amount',
                    'Project.needed_amount',
                    'Project.commission_amount',
                    'Project.reserve_amount',
                    'Project.user_id',
                    'Project.is_allow_over_funding',
                    'Project.name',
                    'Project.project_status_id',
                    'Project.slug',
                    'Project.short_description',
                    'Project.id'
                ) ,
                'recursive' => 2
            ));
            if (($project['Project']['collected_amount']+$projectFund['ProjectFund']['amount']) == $project['Project']['needed_amount'] && !($project['Project']['is_allow_over_funding'])) {
                $updates = array(
                    'Project.collected_amount' => 'Project.collected_amount + ' . $projectFund['ProjectFund']['amount'],
                    'Project.collected_percentage' => '(Project.collected_amount/Project.needed_amount)*100',
                    'Project.project_status_id' => ConstProjectStatus::FundingClosed,
                    'Project.project_fund_goal_reached_date' => "'" . date('Y-m-d H:i:s') . "'",
                );
                // sending Mail to owner
                $owner_user[] = $project['Project']['user_id'];
                $return_owner_lists = $this->Project->_sendAlertOnProjectSuccessful(array_unique($owner_user) , $project, ConstProjectUsers::Owner);
                // send mail to backed
                $pledged_users = Set::extract('/ProjectFund/user_id', $project);
                $pledged_user_lists = $this->Project->_sendAlertOnProjectSuccessful(array_unique($pledged_users) , $project, ConstProjectUsers::Backer, $return_owner_lists);
                // send mail to followers
                $follow_users = Set::extract('/ProjectFollower/user_id', $project);
                $this->Project->_sendAlertOnProjectSuccessful(array_unique($follow_users) , $project, ConstProjectUsers::Follower, $pledged_user_lists);
                // Send mail to admin
                $this->Project->_sendAlertOnProjectStatusToAdmin($project, $project['Project']['project_status_id'], ConstProjectStatus::FundingClosed);
                $this->Project->_executepay($project['Project']['id']);
            } elseif ($project['Project']['collected_amount']+$projectFund['ProjectFund']['amount'] >= $project['Project']['needed_amount']) {
                $updates = array(
                    'Project.collected_amount' => 'Project.collected_amount + ' . $projectFund['ProjectFund']['amount'],
                    'Project.collected_percentage' => '(Project.collected_amount/Project.needed_amount)*100',
                );
                if (($project['Project']['project_status_id'] == ConstProjectStatus::OpenForFunding || $project['Project']['project_status_id'] == ConstProjectStatus::ReserveAmountReached) && $project['Project']['project_status_id'] != ConstProjectStatus::GoalReached) {
                    $updates['Project.project_fund_goal_reached_date'] = "'" . date('Y-m-d H:i:s') . "'";
                    $updates['Project.project_status_id'] = ConstProjectStatus::GoalReached;
                    // sending Mail to owner
                    $owner_user[] = $project['Project']['user_id'];
                    $return_owner_lists = $this->Project->_sendAlertOnProjectGoalReached(array_unique($owner_user) , $project, ConstProjectUsers::Owner);
                    // send mail to backed
                    $pledged_users = Set::extract('/ProjectFund/user_id', $project);
                    $pledged_user_lists = $this->Project->_sendAlertOnProjectGoalReached(array_unique($pledged_users) , $project, ConstProjectUsers::Backer, $return_owner_lists);
                    // send mail to followers
                    $follow_users = Set::extract('/ProjectFollower/user_id', $project);
                    $this->Project->_sendAlertOnProjectGoalReached(array_unique($follow_users) , $project, ConstProjectUsers::Follower, $pledged_user_lists);
                    // Send mail to admin
                    $this->Project->_sendAlertOnProjectStatusToAdmin($project, $project['Project']['project_status_id'], ConstProjectStatus::GoalReached);
					$this->Project->_executepay($project['Project']['id']);
                } elseif ($project['Project']['project_status_id'] == ConstProjectStatus::GoalReached) {
                    $this->Project->_executepay($project['Project']['id']);
                }
            } elseif (!empty($project['Project']['reserve_amount']) && $project['Project']['collected_amount']+$projectFund['ProjectFund']['amount'] >= $project['Project']['reserve_amount']) {
                $updates = array(
                    'Project.collected_amount' => 'Project.collected_amount + ' . $projectFund['ProjectFund']['amount'],
                    'Project.collected_percentage' => '(Project.collected_amount/Project.needed_amount)*100',
                );
                if ($project['Project']['project_status_id'] == ConstProjectStatus::ReserveAmountReached) {
                    $this->Project->_executepay($project['Project']['id']);
                }
                if ($project['Project']['project_status_id'] == ConstProjectStatus::OpenForFunding && $project['Project']['project_status_id'] != ConstProjectStatus::GoalReached && $project['Project']['project_status_id'] != ConstProjectStatus::ReserveAmountReached) {
                    $updates['Project.reserve_reached_date'] = "'" . date('Y-m-d H:i:s') . "'";
                    $updates['Project.project_status_id'] = ConstProjectStatus::ReserveAmountReached;
                    // sending Mail to owner
                    $owner_user[] = $project['Project']['user_id'];
                    $return_owner_lists = $this->Project->_sendAlertOnProjectReserveAmountReached(array_unique($owner_user) , $project, ConstProjectUsers::Owner);
                    // send mail to backed
                    $pledged_users = Set::extract('/ProjectFund/user_id', $project);
                    $pledged_user_lists = $this->Project->_sendAlertOnProjectReserveAmountReached(array_unique($pledged_users) , $project, ConstProjectUsers::Backer, $return_owner_lists);
                    // send mail to followers
                    $follow_users = Set::extract('/ProjectFollower/user_id', $project);
                    $this->Project->_sendAlertOnProjectReserveAmountReached(array_unique($follow_users) , $project, ConstProjectUsers::Follower, $pledged_user_lists);
                    // Send mail to admin
                    $this->Project->_sendAlertOnProjectStatusToAdmin($project, $project['Project']['project_status_id'], ConstProjectStatus::ReserveAmountReached);
                    $this->Project->_executepay($project['Project']['id']);
                }
            } else {
                $updates = array(
                    'Project.collected_amount' => 'Project.collected_amount + ' . $projectFund['ProjectFund']['amount'],
                    'Project.collected_percentage' => '(Project.collected_amount/Project.needed_amount)*100',
                );
            }
            $user_preference = $this->Project->_getPermissionPerference($project['Project']['user_id']);
            if ($user_preference['UserPermissionPreference']['new_fund_notification_mail'] == 1) {
                $this->Project->_sendAlertOnProjectStatus($project, 'New fund notification', $projectFund);
            }
            $user_preference_backer = $this->Project->_getPermissionPerference($projectFund['ProjectFund']['user_id']);
            if ($user_preference_backer['UserPermissionPreference']['new_fund_backer_notification_mail'] == 1) {
                $this->Project->_sendAlertOnProjectStatus($project, 'New fund buyer notification', $projectFund, 'buyer');
            }
            $updates['Project.commission_amount'] = '"' . ($project['Project']['commission_amount']+$projectFund['ProjectFund']['site_fee']) . '"';
            $this->Project->_sendAlertOnProjectStatus($project, 'New fund notification', $projectFund, 'admin');
            $this->Project->Behaviors->detach('Logable');
            $this->Project->updateAll($updates, array(
                'Project.id' => $projectFund['ProjectFund']['project_id']
            ));
            $user = $this->Project->User->UserPermissionPreference->find('first', array(
                'conditions' => array(
                    'UserPermissionPreference.user_id' => $projectFund['ProjectFund']['user_id']
                ) ,
                'recursive' => -1
            ));
            if ($user['UserPermissionPreference']['fb_status_project_pledged']) {
                if ($projectFund['User']['fb_user_id'] > 0) {
                    $fb_message = $projectFund['User']['username'] . ' ' . __l('pledged for ') . ' "' . $project['Project']['name'] . '" in' . ' ' . Configure::read('site.name');
                    $getFBReturn = $this->postOnFacebook($project, $fb_message, 0, $projectFund);
                }
            }
            // post on user twitter
            if ($user['UserPermissionPreference']['twitter_status_new_project']) {
                if (!empty($projectFund['User']['twitter_access_token']) && !empty($projectFund['User']['twitter_access_key'])) {
                    $message = $projectFund['User']['username'] . ' ' . __l('pledged for ') . ' "' . $project['Project']['name'] . '" in' . ' ' . Configure::read('site.name');
                    $xml = $this->OauthConsumer->post('Twitter', $projectFund['User']['twitter_access_token'], $projectFund['User']['twitter_access_key'], 'https://twitter.com/statuses/update.xml', array(
                        'status' => $message
                    ));
                }
            }
            $_dataProjectFund['ProjectFund']['coupon_code'] = $this->_uuid();
            $_dataProjectFund['ProjectFund']['unique_coupon_code'] = $this->_unum();
        }
        $this->Project->ProjectFund->Behaviors->detach('Logable');
        $_dataProjectFund['ProjectFund']['user_id'] = $projectFund['ProjectFund']['user_id'];
        $_dataProjectFund['ProjectFund']['project_id'] = $project_id;
        $this->Project->ProjectFund->save($_dataProjectFund, false);
    }*/
    function postOnFacebook($project = null, $message = null, $admin = null, $projectFund = null)
    {
        if (!empty($project)) {
            $slug = $project['Project']['slug'];
            $image_options = array(
                'dimension' => 'normal_thumb',
                'class' => '',
                'alt' => $project['Project']['name'],
                'title' => $project['Project']['name'],
                'type' => 'jpg'
            );
            if ($admin) {
                $facebook_dest_user_id = Configure::read('facebook.fb_user_id');
                $facebook_dest_access_token = Configure::read('facebook.fb_access_token');
            } else {
                $facebook_dest_user_id = $projectFund['User']['fb_user_id'];
                $facebook_dest_access_token = $projectFund['User']['fb_access_token'];
            }
            App::import('Vendor', 'facebook/facebook');
            $this->facebook = new Facebook(array(
                'appId' => Configure::read('facebook.fb_api_key') ,
                'secret' => Configure::read('facebook.fb_secrect_key') ,
                'cookie' => true
            ));
            if (empty($message)) {
                $message = $project['Project']['name'];
            }
            $image_url = Router::url('/', true) . $this->Project->getImageUrl('Project', $project['Attachment'], $image_options);
            $image_link = Router::url(array(
                'controller' => 'projects',
                'action' => 'view',
                'admin' => false,
                $slug
            ) , true);
            try {
                $getPostCheck = $this->facebook->api('/' . $facebook_dest_user_id . '/feed', 'POST', array(
                    'access_token' => $facebook_dest_access_token,
                    'message' => $message,
                    'picture' => $image_url,
                    'icon' => $image_url,
                    'link' => $image_link,
                    'description' => $project['Project']['short_description']
                ));
            }
            catch(Exception $e) {
                return 2;
            }
        }
    }
    function _savePaidLog($order_id, $paymentDetails, $class = 'ProjectFund', $receiver_count = 2)
    {
        App::import('Model', 'AdaptiveTransactionLog');
        $this->AdaptiveTransactionLog = new AdaptiveTransactionLog();
        $adaptiveTransactionLog['foreign_id'] = $order_id;
        $adaptiveTransactionLog['class'] = $class;
        $adaptiveTransactionLog['timestamp'] = !empty($paymentDetails['responseEnvelope.timestamp'])?$paymentDetails['responseEnvelope.timestamp']:'';
        $adaptiveTransactionLog['ack'] = !empty($paymentDetails['responseEnvelope.ack'])?$paymentDetails['responseEnvelope.ack']:'';
        $adaptiveTransactionLog['correlation_id'] = !empty($paymentDetails['responseEnvelope.correlationId'])?$paymentDetails['responseEnvelope.correlationId']:'';
        $adaptiveTransactionLog['build'] = !empty($paymentDetails['responseEnvelope.build'])?$paymentDetails['responseEnvelope.build']:'';
        $adaptiveTransactionLog['currency_code'] = !empty($paymentDetails['currencyCode'])?$paymentDetails['currencyCode']:'';
        $adaptiveTransactionLog['sender_email'] = !empty($paymentDetails['senderEmail'])?$paymentDetails['senderEmail']:'';
        $adaptiveTransactionLog['status'] = !empty($paymentDetails['status'])?$paymentDetails['status']:'';
        $adaptiveTransactionLog['tracking_id'] = !empty($paymentDetails['trackingId'])?$paymentDetails['trackingId']:'';
        $adaptiveTransactionLog['pay_key'] = !empty($paymentDetails['payKey'])?$paymentDetails['payKey']:'';
        $adaptiveTransactionLog['action_type'] = !empty($paymentDetails['actionType'])?$paymentDetails['actionType']:'';
        $adaptiveTransactionLog['fees_payer'] = !empty($paymentDetails['feesPayer']) ? $paymentDetails['feesPayer']:'';
        $adaptiveTransactionLog['memo'] = !empty($paymentDetails['memo']) ? $paymentDetails['memo'] : '';
        $adaptiveTransactionLog['reverse_all_parallel_payments_on_error'] = !empty($paymentDetails['reverseAllParallelPaymentsOnError'])?$paymentDetails['reverseAllParallelPaymentsOnError']:'';
        for ($i = 0; $i < $receiver_count; $i++) {
            $adaptiveTransactionLog['transaction_id'] = !empty($paymentDetails['paymentInfoList.paymentInfo(' . $i . ').transactionId']) ? $paymentDetails['paymentInfoList.paymentInfo(' . $i . ').transactionId'] : '';
            $adaptiveTransactionLog['transaction_status'] = !empty($paymentDetails['paymentInfoList.paymentInfo(' . $i . ').transactionStatus']) ? $paymentDetails['paymentInfoList.paymentInfo(' . $i . ').transactionStatus'] : '';
            $adaptiveTransactionLog['amount'] = !empty($paymentDetails['paymentInfoList.paymentInfo(' . $i . ').receiver.amount'])?$paymentDetails['paymentInfoList.paymentInfo(' . $i . ').receiver.amount']:'';
            $adaptiveTransactionLog['email'] = !empty($paymentDetails['paymentInfoList.paymentInfo(' . $i . ').receiver.email'])?$paymentDetails['paymentInfoList.paymentInfo(' . $i . ').receiver.email']:'';
            $adaptiveTransactionLog['primary'] = !empty($paymentDetails['paymentInfoList.paymentInfo(' . $i . ').receiver.primary'])?$paymentDetails['paymentInfoList.paymentInfo(' . $i . ').receiver.primary']:'';
            $adaptiveTransactionLog['invoice_id'] = !empty($paymentDetails['paymentInfoList.paymentInfo(' . $i . ').receiver.invoiceId']) ? $paymentDetails['paymentInfoList.paymentInfo(' . $i . ').receiver.invoiceId'] : '';
            $adaptiveTransactionLog['refunded_amount'] = !empty($paymentDetails['paymentInfoList.paymentInfo(' . $i . ').refundedAmount']) ? $paymentDetails['paymentInfoList.paymentInfo(' . $i . ').refundedAmount'] : '';
            $adaptiveTransactionLog['pending_refund'] = !empty($paymentDetails['paymentInfoList.paymentInfo(' . $i . ').pendingRefund']) ? $paymentDetails['paymentInfoList.paymentInfo(' . $i . ').pendingRefund'] : '';
            $adaptiveTransactionLog['sender_transaction_id'] = !empty($paymentDetails['paymentInfoList.paymentInfo(' . $i . ').senderTransactionId']) ? $paymentDetails['paymentInfoList.paymentInfo(' . $i . ').senderTransactionId'] : '';
            $adaptiveTransactionLog['sender_transaction_status'] = !empty($paymentDetails['paymentInfoList.paymentInfo(' . $i . ').senderTransactionStatus']) ? $paymentDetails['paymentInfoList.paymentInfo(' . $i . ').senderTransactionStatus'] : '';
            $this->AdaptiveTransactionLog->create();
            $this->AdaptiveTransactionLog->save($adaptiveTransactionLog);
        }
    }
    function getPaymentDetails($payKey)
    {
        $PaypalPlatform = $this->_getPaypalPlatformObject();
        $transactionId = '';
        $trackingId = '';
        $paymentDetails = $PaypalPlatform->CallPaymentDetails($payKey, $transactionId, $trackingId);
        return $paymentDetails;
    }
    function _getPaypalPlatformObject()
    {
        App::import('Vendor', 'adaptive_paypal/paypal_platform');
        $this->PaypalPlatform = new PaypalPlatform();
        App::import('Model', 'Transaction');
        $this->Transaction = new Transaction();
        $payment_gateway_id = ConstPaymentGateways::PayPal;
        $paymentGateway = $this->Transaction->PaymentGateway->find('first', array(
            'conditions' => array(
                'PaymentGateway.id' => $payment_gateway_id,
            ) ,
            'contain' => array(
                'PaymentGatewaySetting' => array(
                    'fields' => array(
                        'PaymentGatewaySetting.key',
                        'PaymentGatewaySetting.test_mode_value',
                        'PaymentGatewaySetting.live_mode_value',
                    ) ,
                ) ,
            ) ,
            'recursive' => 1
        ));
        if (!empty($paymentGateway['PaymentGatewaySetting'])) {
            foreach($paymentGateway['PaymentGatewaySetting'] as $paymentGatewaySetting) {
                $gateway_settings_options[$paymentGatewaySetting['key']] = $paymentGateway['PaymentGateway']['is_test_mode'] ? $paymentGatewaySetting['test_mode_value'] : $paymentGatewaySetting['live_mode_value'];
            }
        }
        $gateway_settings_options['is_test_mode'] = $paymentGateway['PaymentGateway']['is_test_mode'];
        $this->PaypalPlatform->settings($gateway_settings_options);
        return $this->PaypalPlatform;
    }
    function _parse_array_query($array, $convention = '%s')
    {
        if (count($array) == 0) {
            return '';
        } else {
            $query = '';
            foreach($array as $key => $value) {
                if (is_array($value)) {
                    $new_convention = sprintf($convention, $key) . '[%s]';
                    $query.= $this->_parse_array_query($value, $new_convention);
                } else {
                    $key = urlencode($key);
                    $value = urlencode($value);
                    $query.= sprintf($convention, $key) . "=$value&";
                }
            }
            return $query;
        }
    }
	function cancelPreapproval($preapprovalKey)
    {
        $PaypalPlatform = $this->_getPaypalPlatformObject();
        $paymentDetails = $PaypalPlatform->CallCancelPreapproval($preapprovalKey);
        return $paymentDetails;
    }
    function _saveIPNLog()
    {
        App::import('Model', 'AdaptiveIpnLog');
        $this->AdaptiveIpnLog = new AdaptiveIpnLog();
        $paypal_post_vars_in_str = $this->_parse_array_query($_POST);
        $adaptiveIpnLog['post_variable'] = $paypal_post_vars_in_str;
        $adaptiveIpnLog['ip'] = RequestHandlerComponent::getClientIP();
        $adaptiveIpnLog['host'] = gethostbyaddr($adaptiveIpnLog['ip']);
        $this->AdaptiveIpnLog->create();
        $this->AdaptiveIpnLog->save($adaptiveIpnLog);
    }
    function _gatewayFeeSettings()
    {
        $feesPayer = '';
        if (Configure::read('Project.payment_gateway_flow_id') == ConstPaymentGatewayFlow::BuyerSellerSite) {
            if (Configure::read('Project.payment_gateway_fee_id') == ConstPaymentGatewayFee::Seller) {
                $feesPayer = 'PRIMARYRECEIVER';
            } else if (Configure::read('Project.payment_gateway_fee_id') == ConstPaymentGatewayFee::Site) {
                $feesPayer = 'SECONDARYONLY';
            } else if (Configure::read('Project.payment_gateway_fee_id') == ConstPaymentGatewayFee::SiteAndSeller) {
                $feesPayer = 'EACHRECEIVER';
            }
        } else if (Configure::read('Project.payment_gateway_flow_id') == ConstPaymentGatewayFlow::BuyerSiteSeller) {
            if (Configure::read('Project.payment_gateway_fee_id') == ConstPaymentGatewayFee::Seller) {
                $feesPayer = 'SECONDARYONLY';
            } else if (Configure::read('Project.payment_gateway_fee_id') == ConstPaymentGatewayFee::Site) {
                $feesPayer = 'PRIMARYRECEIVER';
            } else if (Configure::read('Project.payment_gateway_fee_id') == ConstPaymentGatewayFee::SiteAndSeller) {
                $feesPayer = 'EACHRECEIVER';
            }
        }
        return $feesPayer;
    }
    function processPaypalConnect($user_id)
    {
        App::import('Model', 'User');
        $this->User = new User();
        $user = $gig = $this->User->find('first', array(
            'conditions' => array(
                'User.id' => $user_id
            ) ,
            'recursive' => -1
        ));
        if (empty($user)) {
            $this->cakeError('error404');
        }
        $PaypalPlatform = $this->_getPaypalPlatformObject();
        $currencyCode = Configure::read('site.currency_code');
        $startingDate = date('c');
        $endingDate = date('c', strtotime('+1 year'));
        $this->data['UserPaypalConnection']['user_id'] = $user_id;
        $this->data['UserPaypalConnection']['valid_from'] = $startingDate;
        $this->data['UserPaypalConnection']['valid_to'] = $endingDate;
        $this->User->UserPaypalConnection->save($this->data);
        $user_paypal_connection_id = $this->data['UserPaypalConnection']['id'] = $this->User->UserPaypalConnection->id;
        $maxTotalAmountOfAllPayments = "2000";
        $senderEmail = "";
        $maxNumberOfPayments = "";
        $paymentPeriod = "";
        $dateOfMonth = "";
        $dayOfWeek = "";
        $maxAmountPerPayment = "";
        $maxNumberOfPaymentsPerPeriod = "";
        $pinType = "";
        $cancelUrl = Router::url('/', true) . 'payments/cancel_connect/' . $user_paypal_connection_id;
        $returnUrl = Router::url('/', true) . 'payments/success_connect/' . $user_paypal_connection_id;
        $ipnNotificationUrl = Router::url('/', true) . 'payments/processconnect/' . $user_paypal_connection_id;
        $resArray = $PaypalPlatform->CallPreapproval($returnUrl, $cancelUrl, $currencyCode, $startingDate, $endingDate, $maxTotalAmountOfAllPayments, $senderEmail, $maxNumberOfPayments, $paymentPeriod, $dateOfMonth, $dayOfWeek, $maxAmountPerPayment, $maxNumberOfPaymentsPerPeriod, $pinType, $ipnNotificationUrl);
        $ack = strtoupper($resArray["responseEnvelope.ack"]);
        if ($ack == "SUCCESS") {
            $this->data['UserPaypalConnection']['pre_approval_key'] = $resArray["preapprovalKey"];
            $this->User->UserPaypalConnection->save($this->data);
            $cmd = "cmd=_ap-preapproval&preapprovalkey=" . urldecode($resArray["preapprovalKey"]);
            $PaypalPlatform->RedirectToPayPal($cmd);
        } else {
            //Display a user friendly Error on the page using any of the following error information returned by PayPal
            //TODO - There can be more than 1 error, so check for "error(1).errorId", then "error(2).errorId", and so on until you find no more errors.
            $ErrorCode = urldecode($resArray["error(0).errorId"]);
            $ErrorMsg = urldecode($resArray["error(0).message"]);
            $ErrorDomain = urldecode($resArray["error(0).domain"]);
            $ErrorSeverity = urldecode($resArray["error(0).severity"]);
            $ErrorCategory = urldecode($resArray["error(0).category"]);
        }
    }
    function updateUserConnection($paypalConnection, $userPaypalConnection)
    {
        App::import('Model', 'User');
        $this->User = new User();
        $defaultUserPaypalConnection = $this->User->UserPaypalConnection->find('first', array(
            'conditions' => array(
                'UserPaypalConnection.user_id' => $userPaypalConnection['UserPaypalConnection']['user_id'],
                'UserPaypalConnection.is_default' => 1
            ) ,
            'fields' => array(
                'COUNT(UserPaypalConnection.id) AS default_count'
            ) ,
            'recursive' => -1
        ));		
		
        if (empty($defaultUserPaypalConnection[0]['default_count'])) {
            $this->data['UserPaypalConnection']['is_default'] = 1;
        }
		
		$defaultUserPaypalConnection1 = $this->User->UserPaypalConnection->find('all', array(
            'conditions' => array(
                'UserPaypalConnection.sender_email' => $paypalConnection['senderEmail'],
                'UserPaypalConnection.is_active' => 1
            ) ,            
            'recursive' => -1
        ));		
		
        $this->data['UserPaypalConnection']['sender_email'] = $paypalConnection['senderEmail'];
        $this->data['UserPaypalConnection']['amount'] = $paypalConnection['maxTotalAmountOfAllPayments'];
        $this->data['UserPaypalConnection']['is_active'] = 1;
        $this->data['UserPaypalConnection']['id'] = $userPaypalConnection['UserPaypalConnection']['id'];
		if(empty($defaultUserPaypalConnection1))
		{
        	$this->User->UserPaypalConnection->save($this->data, false);
		}		
    }
    function getPreapprovalDetails($preapprovalKey)
    {
        $PaypalPlatform = $this->_getPaypalPlatformObject();
        $paypalConnection = $PaypalPlatform->CallPreapprovalDetails($preapprovalKey);
        return $paypalConnection;
    }
    function getMerchantReferralURL()
    {
        App::import('Model', 'Transaction');
        $this->Transaction = new Transaction();
        $payment_gateway_id = ConstPaymentGateways::PayPal;
        $paymentGateway = $this->Transaction->PaymentGateway->find('first', array(
            'conditions' => array(
                'PaymentGateway.id' => $payment_gateway_id,
            ) ,
            'contain' => array(
                'PaymentGatewaySetting' => array(
                    'fields' => array(
                        'PaymentGatewaySetting.key',
                        'PaymentGatewaySetting.test_mode_value',
                        'PaymentGatewaySetting.live_mode_value',
                    ) ,
                ) ,
            ) ,
            'recursive' => 1
        ));
        if (!empty($paymentGateway['PaymentGatewaySetting'])) {
            foreach($paymentGateway['PaymentGatewaySetting'] as $paymentGatewaySetting) {
                $gateway_settings_options[$paymentGatewaySetting['key']] = $paymentGateway['PaymentGateway']['is_test_mode'] ? $paymentGatewaySetting['test_mode_value'] : $paymentGatewaySetting['live_mode_value'];
            }
        }
        if (!empty($paymentGateway['PaymentGateway']['is_test_mode'])) {
            return 'https://www.sandbox.paypal.com/us/mrb/pal=' . $gateway_settings_options['MRB_ID'];
        } else {
            return 'https://www.paypal.com/us/mrb/pal=' . $gateway_settings_options['MRB_ID'];
        }
    }
    function createPaypalAccount($paypalAccount)
    {
        App::import('Model', 'User');
        $this->User = new User();
        $PaypalPlatform = $this->_getPaypalPlatformObject();
        $cancelUrl = Router::url('/', true) . 'payments/cancel_account';
        $returnUrl = Router::url('/', true) . 'payments/success_account';
        $referralId = '';
        $notificationURL = '';
        $preferredLanguageCode = 'en_US';
        $accountType = $paypalAccount['PaypalAccount']['payment_types'];
        $firstName = $paypalAccount['PaypalAccount']['first_name'];
        $lastName = $paypalAccount['PaypalAccount']['last_name'];
        $dateOfBirth = $paypalAccount['PaypalAccount']['dob'];
        $address1 = $paypalAccount['PaypalAccount']['address1'];
        $address2 = $paypalAccount['PaypalAccount']['address2'];
        $city = $paypalAccount['PaypalAccount']['city'];
        $state = $paypalAccount['PaypalAccount']['state'];
        $zip = $paypalAccount['PaypalAccount']['zip'];
        $countryCode = $paypalAccount['PaypalCountry']['code'];
        $citizenshipCountryCode = $paypalAccount['PaypalCitizenshipCountry']['code'];
        $contactPhoneNumber = $paypalAccount['PaypalAccount']['phone'];
        $currencyCode = $paypalAccount['PaypalAccount']['currency_code'];
        $emailAddress = $paypalAccount['PaypalAccount']['email'];
        $resArray = $PaypalPlatform->CallCreateAccount($preferredLanguageCode, $accountType, $firstName, $lastName, $dateOfBirth, $address1, $address2, $city, $state, $zip, $countryCode, $citizenshipCountryCode, $contactPhoneNumber, $currencyCode, $emailAddress, $returnUrl, $cancelUrl, $notificationURL, $referralId);
        $ack = strtoupper($resArray["responseEnvelope.ack"]);
        $return['error'] = 0;
        if ($ack == "SUCCESS") {
            $data['PaypalAccount']['id'] = $paypalAccount['PaypalAccount']['id'];
            $data['PaypalAccount']['create_account_key'] = $resArray["createAccountKey"];
            $this->User->PaypalAccount->save($data, false);
            header('Location: ' . $resArray["redirectURL"]);
            exit;
        } else {
            $ErrorMsg = urldecode($resArray["error(0).message"]);
            $return['error_message'] = $ErrorMsg;
            $return['error'] = 1;
        }
        return $return;
    }
    function getVerifiedStatus($data)
    {
        $PaypalPlatform = $this->_getPaypalPlatformObject();
        $paymentDetails = $PaypalPlatform->CallGetVerifiedStatus($data['paypal_account'], $data['paypal_first_name'], $data['paypal_last_name']);
        return $paymentDetails;
    }
    function refundProjectFund($order_id, $is_from_paypal = ConstResponseFrom::site)
    {
        App::import('Model', 'Project');
        $this->Project = new Project();
        $projectFund = $this->Project->ProjectFund->find('first', array(
            'conditions' => array(
                'ProjectFund.id' => $order_id,
            ) ,
            'contain' => array(
                'Project',
                'User',
            ) ,
            'recursive' => 2,
        ));
        if (empty($projectFund)) {
            $this->cakeError('error404');
        }
        $PaypalPlatform = $this->_getPaypalPlatformObject();
        if ($projectFund['ProjectFund']['payment_gateway_id'] == ConstPaymentGateways::PayPal) {
            $paymentDetails = $PaypalPlatform->CallCancelPreapproval($projectFund['ProjectFund']['pay_key']);
            $ack = strtoupper($paymentDetails["responseEnvelope.ack"]);
            if ($ack == "SUCCESS") {
                //$this->_saveRefundLog($order_id, $paymentDetails);
                    $return['error'] = 0;
                    $updates = array(
                        'Project.commission_amount' => 'Project.commission_amount - ' . $projectFund['ProjectFund']['site_fee'],
                        'Project.collected_amount' => 'Project.collected_amount - ' . $projectFund['ProjectFund']['amount'],
                        'Project.collected_percentage' => '(Project.collected_amount/Project.needed_amount)*100'
                    );
                    // to save in projects table
                    $project_data['Project']['id'] = $projectFund['Project']['id'];
                    $project_data['Project']['commission_amount'] = $projectFund['Project']['commission_amount'] - $projectFund['ProjectFund']['site_fee'];
                    $project_data['Project']['collected_amount'] = $projectFund['Project']['collected_amount'] - $projectFund['ProjectFund']['amount'];
                    $project_data['Project']['collected_percentage'] = round((($project_data['Project']['collected_amount']/$projectFund['Project']['needed_amount'])*100), 2);
                    $this->Project->Behaviors->detach('Logable');
                    $this->Project->save($project_data, false);
                    $_projectFundData['id'] = $projectFund['ProjectFund']['id'];
                    $_projectFundData['project_id'] = $projectFund['ProjectFund']['project_id'];
                    $_projectFundData['is_refunded'] = 1;
                    $_projectFundData['is_cancelled'] = 1;
                    $_projectFundData['is_canceled_from_paypal'] = $is_from_paypal;
                    $_projectFundData['user_id'] = $projectFund['ProjectFund']['user_id'];
                    $this->Project->ProjectFund->Behaviors->detach('Logable');
                    $this->Project->ProjectFund->save($_projectFundData, false);
                    // Notify mail for refunded
                    $user_preference = $this->Project->_getPermissionPerference($projectFund['ProjectFund']['user_id']);
                    if ($user_preference['UserPermissionPreference']['project_refund_notification_mail'] == 1) {
                        $this->Project->_sendAlertOnProjectStatus($projectFund, 'Project refund notification Paypal', '', '', 'PayPal');
                    }
                    $data['Transaction']['foreign_id'] = $projectFund['ProjectFund']['id'];
                    $data['Transaction']['class'] = 'ProjectFund';
                    $data['Transaction']['user_id'] = $projectFund['ProjectFund']['user_id'];
                    $data['Transaction']['amount'] = $projectFund['ProjectFund']['amount'];
                    $data['Transaction']['payment_gateway_id'] = $projectFund['ProjectFund']['payment_gateway_id'];
                    $data['Transaction']['transaction_type_id'] = ConstTransactionTypes::Refunding;
                    $this->Project->User->Transaction->create();
                    $this->Project->User->Transaction->save($data);
                    $data1['Transaction']['foreign_id'] = $projectFund['ProjectFund']['id'];
                    $data1['Transaction']['class'] = 'ProjectFund';
                    $data1['Transaction']['user_id'] = $projectFund['Project']['user_id'];
                    $data1['Transaction']['amount'] = $projectFund['ProjectFund']['amount'];
                    $data1['Transaction']['payment_gateway_id'] = $projectFund['ProjectFund']['payment_gateway_id'];
                    $data1['Transaction']['transaction_type_id'] = ConstTransactionTypes::Refunded;
                    $this->Project->User->Transaction->create();
                    $this->Project->User->Transaction->save($data1);

                    $admin_data['Transaction']['foreign_id'] = $projectFund['ProjectFund']['id'];
                    $admin_data['Transaction']['class'] = 'ProjectFund';
                    $admin_data['Transaction']['user_id'] = ConstUserIds::Admin;
                    $admin_data['Transaction']['amount'] = $projectFund['ProjectFund']['site_fee'];
                    $admin_data['Transaction']['payment_gateway_id'] = $projectFund['ProjectFund']['payment_gateway_id'];
                    $admin_data['Transaction']['transaction_type_id'] = ConstTransactionTypes::Refunded;
                    $this->Project->User->Transaction->create();
                    $this->Project->User->Transaction->save($admin_data);
                
            } else {
                $return['error'] = 1;
            }
        } else if ($projectFund['ProjectFund']['payment_gateway_id'] == ConstPaymentGateways::Wallet) {
            $return['error'] = 0;
            $update_blocked_balance = $projectFund['User']['blocked_amount']-$projectFund['ProjectFund']['amount'];
            $update_available_balance = $projectFund['User']['available_wallet_amount']+$projectFund['ProjectFund']['amount'];
            //update funder user
            $this->Project->User->updateAll(array(
                'User.blocked_amount' => "'" . $update_blocked_balance . "'",
                'User.available_wallet_amount' => "'" . $update_available_balance . "'",
            ) , array(
                'User.id' => $projectFund['ProjectFund']['user_id']
            ));
            $updates = array(
                'Project.commission_amount' => 'Project.commission_amount - ' . $projectFund['ProjectFund']['site_fee'],
                'Project.collected_amount' => 'Project.collected_amount - ' . $projectFund['ProjectFund']['amount'],
                'Project.collected_percentage' => '(Project.collected_amount/Project.needed_amount)*100'
            );
            $this->Project->Behaviors->detach('Logable');
            $this->Project->updateAll($updates, array(
                'Project.id' => $projectFund['ProjectFund']['project_id']
            ));
            $_projectFundData['id'] = $projectFund['ProjectFund']['id'];
            $_projectFundData['project_id'] = $projectFund['ProjectFund']['project_id'];
            $_projectFundData['is_refunded'] = 1;
            $_projectFundData['user_id'] = $projectFund['ProjectFund']['user_id'];
            $this->Project->ProjectFund->Behaviors->detach('Logable');
            $this->Project->ProjectFund->save($_projectFundData, false);
            // Notify mail for refunded
            $user_preference = $this->Project->_getPermissionPerference($projectFund['ProjectFund']['user_id']);
            if ($user_preference['UserPermissionPreference']['project_refund_notification_mail'] == 1) {
                $this->Project->_sendAlertOnProjectStatus($projectFund, 'Project refund notification', '', '', 'Wallet');
            }
            $data['Transaction']['foreign_id'] = $projectFund['ProjectFund']['id'];
            $data['Transaction']['class'] = 'ProjectFund';
            $data['Transaction']['user_id'] = $projectFund['ProjectFund']['user_id'];
            $data['Transaction']['amount'] = $projectFund['ProjectFund']['amount'];
            $data['Transaction']['payment_gateway_id'] = $projectFund['ProjectFund']['payment_gateway_id'];
            $data['Transaction']['transaction_type_id'] = ConstTransactionTypes::Refunding;
            $this->Project->User->Transaction->create();
            $this->Project->User->Transaction->save($data);
            $data1['Transaction']['foreign_id'] = $projectFund['ProjectFund']['id'];
            $data1['Transaction']['class'] = 'ProjectFund';
            $data1['Transaction']['user_id'] = $projectFund['Project']['user_id'];
            $data1['Transaction']['amount'] = $projectFund['ProjectFund']['amount'];
            $data1['Transaction']['payment_gateway_id'] = $projectFund['ProjectFund']['payment_gateway_id'];
            $data1['Transaction']['transaction_type_id'] = ConstTransactionTypes::Refunded;
            $this->Project->User->Transaction->create();
            $this->Project->User->Transaction->save($data1);

            $admin_data['Transaction']['foreign_id'] = $projectFund['ProjectFund']['id'];
            $admin_data['Transaction']['class'] = 'ProjectFund';
            $admin_data['Transaction']['user_id'] = ConstUserIds::Admin;
            $admin_data['Transaction']['amount'] = $projectFund['ProjectFund']['site_fee'];
            $admin_data['Transaction']['payment_gateway_id'] = $projectFund['ProjectFund']['payment_gateway_id'];
            $admin_data['Transaction']['transaction_type_id'] = ConstTransactionTypes::Refunded;
            $this->Project->User->Transaction->create();
            $this->Project->User->Transaction->save($admin_data);
        }
        return $return;
    }
    function _saveRefundLog($order_id, $paymentDetails)
    {
        App::import('Model', 'AdaptiveTransactionLog');
        $this->AdaptiveTransactionLog = new AdaptiveTransactionLog();
        $adaptiveTransactionLog['foreign_id'] = $order_id;
        $adaptiveTransactionLog['class'] = 'ProjectFund';
        $adaptiveTransactionLog['timestamp'] = $paymentDetails['responseEnvelope.timestamp'];
        $adaptiveTransactionLog['ack'] = $paymentDetails['responseEnvelope.ack'];
        $adaptiveTransactionLog['correlation_id'] = $paymentDetails['responseEnvelope.correlationId'];
        $adaptiveTransactionLog['build'] = $paymentDetails['responseEnvelope.build'];
        $adaptiveTransactionLog['currency_code'] = $paymentDetails['currencyCode'];
        $paypal_post_vars_in_str = '';
        foreach($paymentDetails as $key => $value) {
            $value = urlencode(stripslashes($value));
            $paypal_post_vars_in_str.= "&$key=$value";
        }
        $adaptiveTransactionLog['paypal_post_vars'] = $paypal_post_vars_in_str;
        for ($i = 0; $i < 2; $i++) {
            $adaptiveTransactionLog['amount'] = $paymentDetails['refundInfoList.refundInfo(' . $i . ').receiver.amount'];
            $adaptiveTransactionLog['email'] = $paymentDetails['refundInfoList.refundInfo(' . $i . ').receiver.email'];
            $adaptiveTransactionLog['refund_status'] = $paymentDetails['refundInfoList.refundInfo(' . $i . ').refundStatus'];
            $adaptiveTransactionLog['refund_net_amount'] = !empty($paymentDetails['refundInfoList.refundInfo(' . $i . ').refundNetAmount']) ? $paymentDetails['refundInfoList.refundInfo(' . $i . ').refundNetAmount'] : '';
            $adaptiveTransactionLog['refund_fee_amount'] = !empty($paymentDetails['refundInfoList.refundInfo(' . $i . ').refundFeeAmount']) ? $paymentDetails['refundInfoList.refundInfo(' . $i . ').refundFeeAmount'] : '';
            $adaptiveTransactionLog['refund_gross_amount'] = !empty($paymentDetails['refundInfoList.refundInfo(' . $i . ').refundGrossAmount']) ? $paymentDetails['refundInfoList.refundInfo(' . $i . ').refundGrossAmount'] : '';
            $adaptiveTransactionLog['total_of_alll_refunds'] = !empty($paymentDetails['refundInfoList.refundInfo(' . $i . ').totalOfAllRefunds']) ? $paymentDetails['refundInfoList.refundInfo(' . $i . ').totalOfAllRefunds'] : '';
            $adaptiveTransactionLog['refund_has_become_full'] = !empty($paymentDetails['refundInfoList.refundInfo(' . $i . ').refundHasBecomeFull']) ? $paymentDetails['refundInfoList.refundInfo(' . $i . ').refundHasBecomeFull'] : '';
            $adaptiveTransactionLog['encrypted_refund_transaction_id'] = !empty($paymentDetails['refundInfoList.refundInfo(' . $i . ').encryptedRefundTransactionId']) ? $paymentDetails['refundInfoList.refundInfo(' . $i . ').encryptedRefundTransactionId'] : '';
            $adaptiveTransactionLog['refund_transaction_status'] = !empty($paymentDetails['refundInfoList.refundInfo(' . $i . ').refundTransactionStatus']) ? $paymentDetails['refundInfoList.refundInfo(' . $i . ').refundTransactionStatus'] : '';
            $this->AdaptiveTransactionLog->create();
            $this->AdaptiveTransactionLog->save($adaptiveTransactionLog);
        }
    }
 /*   function executeProjectFund($order_id)
    {
        App::import('Model', 'Project');
        $this->Project = new Project();
        $projectFund = $this->Project->ProjectFund->find('first', array(
            'conditions' => array(
                'ProjectFund.id' => $order_id,
            ) ,
            'contains' => array(
                'User',
                'Project',
            ) ,
            'recursive' => 1,
        ));
        if (empty($projectFund)) {
            $this->cakeError('error404');
        }
        if (!empty($projectFund['ProjectFund']['is_delayed_chained_payment']) && $projectFund['ProjectFund']['payment_gateway_id'] == ConstPaymentGateways::PayPal) {
            $itemDetail['payKey'] = $projectFund['ProjectFund']['pay_key'];
            $PaypalPlatform = $this->_getPaypalPlatformObject();
            $rsArray = $PaypalPlatform->CallExecutePayment($itemDetail['payKey']);
            $ack = strtoupper($rsArray["responseEnvelope.ack"]);
            if ($ack == "SUCCESS") {
                if (strtoupper($rsArray['paymentExecStatus']) == 'COMPLETED') {
                    $return['error'] = 0;
                    $_projectFundData['id'] = $projectFund['ProjectFund']['id'];
                    $_projectFundData['is_paid'] = 1;
                    $_projectFundData['user_id'] = $projectFund['ProjectFund']['user_id'];
                    $_projectFundData['project_id'] = $projectFund['ProjectFund']['project_id'];
                    $this->Project->Behaviors->detach('Logable');
                    $this->Project->ProjectFund->save($_projectFundData, false);
                } else {
                    $return['error'] = 1;
                }
            } else {
                $return['error'] = 1;
            }
        } else if ((empty($projectFund['ProjectFund']['is_delayed_chained_payment']) && $projectFund['ProjectFund']['payment_gateway_id'] == ConstPaymentGateways::PayPal) || $projectFund['ProjectFund']['payment_gateway_id'] == ConstPaymentGateways::Wallet) {
            $update_user_balance = $projectFund['User']['blocked_amount']-$projectFund['ProjectFund']['amount'];
            //update funder user
			if ($projectFund['ProjectFund']['payment_gateway_id'] == ConstPaymentGateways::Wallet) {
				$this->Project->User->updateAll(array(
					'User.blocked_amount' => "'" . $update_user_balance . "'",
				) , array(
					'User.id' => $projectFund['ProjectFund']['user_id']
				));
			}
            $user_info = $this->Project->User->find('first', array(
                'conditions' => array(
                    'User.id' => $projectFund['Project']['user_id']
                ) ,
                'fields' => array(
                    'User.id',
                    'User.username',
                    'User.available_balance_amount',
                    'User.available_wallet_amount',
                ) ,
                'recursive' => -1
            ));
            $update_project_owner_balance = $user_info['User']['available_wallet_amount']+$projectFund['ProjectFund']['amount'];
            //update project owner
            $this->Project->User->updateAll(array(
                'User.available_wallet_amount' => "'" . $update_project_owner_balance . "'",
            ) , array(
                'User.id' => $projectFund['Project']['user_id']
            ));
            $return['error'] = 0;
            $_projectFundData['ProjectFund']['id'] = $order_id;
            $_projectFundData['ProjectFund']['is_paid'] = '1';
            $_projectFundData['ProjectFund']['user_id'] = $projectFund['ProjectFund']['user_id'];
            $_projectFundData['ProjectFund']['project_id'] = $projectFund['ProjectFund']['project_id'];
            $this->Project->Behaviors->detach('Logable');
            $this->Project->ProjectFund->save($_projectFundData, false);
        }
        return $return;
    }*/
    function payUser($data)
    {
        App::import('Model', 'User');
        $this->User = new User();
        App::import('Vendor', 'adaptive_paypal/paypal_platform');
        $this->PaypalPlatform = new PaypalPlatform();
        $payment_gateway_id = ConstPaymentGateways::PayPal;
        $paymentGateway = $this->User->Transaction->PaymentGateway->find('first', array(
            'conditions' => array(
                'PaymentGateway.id' => $payment_gateway_id,
            ) ,
            'contain' => array(
                'PaymentGatewaySetting' => array(
                    'fields' => array(
                        'PaymentGatewaySetting.key',
                        'PaymentGatewaySetting.test_mode_value',
                        'PaymentGatewaySetting.live_mode_value',
                    ) ,
                ) ,
            ) ,
            'recursive' => 1
        ));
        if (!empty($paymentGateway['PaymentGatewaySetting'])) {
            foreach($paymentGateway['PaymentGatewaySetting'] as $paymentGatewaySetting) {
                $gateway_settings_options[$paymentGatewaySetting['key']] = $paymentGateway['PaymentGateway']['is_test_mode'] ? $paymentGatewaySetting['test_mode_value'] : $paymentGatewaySetting['live_mode_value'];
            }
        }
        $gateway_settings_options['is_test_mode'] = $paymentGateway['PaymentGateway']['is_test_mode'];
        $this->PaypalPlatform->settings($gateway_settings_options);
        $user_id = $data['user_id'];
        // Request specific required fields
        $actionType = "PAY";
        $cancelUrl = Router::url('/', true) . 'payments/cancel_userpayment/' . $user_id;
        $returnUrl = Router::url('/', true) . 'payments/success_userpayment/' . $user_id;
        $ipnNotificationUrl = Router::url('/', true) . 'payments/processuserpayment/' . $user_id;
        $currencyCode = Configure::read('site.currency_code');
        $receiverEmailArray = array(
            $gateway_settings_options['payee_account']
        );
        $receiverAmountArray = array(
            $data['amount']
        );
        $receiverPrimaryArray = array();
        $receiverInvoiceIdArray = array(
            md5('ProjectPay_' . date('YmdHis'))
        );
        $senderEmail = '';
        $feesPayer = 'EACHRECEIVER';
        if (Configure::read('User.signup_fee_payeer') == ConstProjectPaymentGatewayFee::User) {
            $feesPayer = 'SENDER';
        }
        $memo = '';
        $pin = '';
        $preapprovalKey = '';
        $reverseAllParallelPaymentsOnError = '';
        $trackingId = $this->PaypalPlatform->generateTrackingID();
        // Make the Pay API call
        $resArray = $this->PaypalPlatform->CallPay($actionType, $cancelUrl, $returnUrl, $currencyCode, $receiverEmailArray, $receiverAmountArray, $receiverPrimaryArray, $receiverInvoiceIdArray, $feesPayer, $ipnNotificationUrl, $memo, $pin, $preapprovalKey, $reverseAllParallelPaymentsOnError, $senderEmail, $trackingId);
        $ack = strtoupper($resArray["responseEnvelope.ack"]);
        $return['error'] = 0;
        if ($ack == "SUCCESS") {
            $this->CustomizePaymentPage($resArray["payKey"]);
            $Userdata['id'] = $user_id;
            $Userdata['pay_key'] = $resArray["payKey"];
            $this->User->Behaviors->detach('Logable');
            $this->User->save($Userdata, false);
            $cmd = "cmd=_ap-payment&paykey=" . urldecode($resArray["payKey"]);
            $this->PaypalPlatform->RedirectToPayPal($cmd);
        } else {
            $ErrorMsg = urldecode($resArray["error(0).message"]);
            $return['error_message'] = $ErrorMsg;
            $return['error'] = 1;
        }
        return $return;
    }
    function processUserWalletPayment($add_to_wallet_id)
    {
        $this->_saveIPNLog();
        App::import('Model', 'UserAddWalletAmount');
        $this->UserAddWalletAmount = new UserAddWalletAmount();
        App::import('Model', 'User');
        $this->User = new User();
        $addWalletAmount = $this->UserAddWalletAmount->find('first', array(
            'conditions' => array(
                'UserAddWalletAmount.id' => $add_to_wallet_id
            ) ,
            'contain' => array(
                'User' => array(
                    'fields' => array(
                        'User.id',
                        'User.username',
                        'User.available_balance_amount',
                        'User.available_wallet_amount',
                    ) ,
                ) ,
            ) ,
            'recursive' => 0
        ));
        if (empty($addWalletAmount)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $paymentDetails = $this->getPaymentDetails($addWalletAmount['UserAddWalletAmount']['pay_key']);
        if ($paymentDetails['status'] == 'INCOMPLETE' || $paymentDetails['status'] == 'COMPLETED') {
            $this->_savePaidLog($add_to_wallet_id, $paymentDetails, 'user', 1);

            if ($this->UserAddWalletAmount->find('count', array(
            'conditions' => array(
                'UserAddWalletAmount.id' => $add_to_wallet_id,
                'UserAddWalletAmount.is_success' => 0
            ) ,
            'recursive' => -1
        ))) {
				$addWalletAmountUpdate['UserAddWalletAmount']['is_success'] = 1;
                $data['Transaction']['user_id'] = $addWalletAmount['UserAddWalletAmount']['user_id'];
                $data['Transaction']['foreign_id'] = ConstUserIds::Admin;
                $data['Transaction']['class'] = 'User';
                $data['Transaction']['amount'] = $addWalletAmount['UserAddWalletAmount']['amount'];
                $data['Transaction']['payment_gateway_id'] = ConstPaymentGateways::Wallet;
                $data['Transaction']['description'] = 'Payment Success';
                $data['Transaction']['transaction_type_id'] = ConstTransactionTypes::AddedToWallet;
                $this->User->Transaction->create();
                $transaction_id = $this->User->Transaction->save($data);

                $admin_data = $data;
                $admin_data['Transaction']['user_id'] = ConstUserIds::Admin;;
                $admin_data['Transaction']['transaction_type_id'] = ConstTransactionTypes::AddedToWallet;
                $this->User->Transaction->create();
                $transaction_id = $this->User->Transaction->save($admin_data);
                
                $User['id'] = $addWalletAmount['UserAddWalletAmount']['user_id'];
                $User['available_wallet_amount'] = $addWalletAmount['User']['available_wallet_amount']+$addWalletAmount['UserAddWalletAmount']['amount'];
                $this->User->save($User, false);
                $addWalletAmountUpdate['UserAddWalletAmount']['id'] = $add_to_wallet_id;
                $this->UserAddWalletAmount->save($addWalletAmountUpdate, false);
                return true;
            }
        }
    }
    function processUserPayment($user_id)
    {
        $this->_saveIPNLog();
        App::import('Model', 'User');
        $this->User = new User();
        $user = $this->User->find('first', array(
            'conditions' => array(
                'User.id = ' => $user_id,
            ) ,
            'recursive' => -1,
        ));
        if (empty($user)) {
            $this->cakeError('error404');
        }
        $paymentDetails = $this->getPaymentDetails($user['User']['pay_key']);
        App::import('Model', 'AdaptiveTransactionLog');
            $this->AdaptiveTransactionLog = new AdaptiveTransactionLog();
            $previous_log = $this->AdaptiveTransactionLog->find('first', array(
            'conditions' => array(
                'AdaptiveTransactionLog.transaction_id' => $paymentDetails['paymentInfoList.paymentInfo(0).transactionId'],
            ) ,
            'recursive' => -1,
            ));
            $this->log('Previous entry');
            $this->log($previous_log);
            if(empty($previous_log))
            {
            $this->log('Entered');
        if ($paymentDetails['status'] == 'COMPLETED' && ($user['User']['is_active'] == 0 && $user['User']['is_paid'] == 0)) {
            $data['Transaction']['foreign_id'] = $user['User']['id'];
            $data['Transaction']['user_id'] = $user['User']['id'];
            $data['Transaction']['class'] = 'User';
            $data['Transaction']['amount'] = $paymentDetails['paymentInfoList.paymentInfo(0).receiver.amount'];
            $data['Transaction']['payment_gateway_id'] = ConstPaymentGateways::PayPal;
            $data['Transaction']['transaction_type_id'] = ConstTransactionTypes::User;
            $this->User->Transaction->create();
             $this->User->Transaction->save($data);
             $admin_data['Transaction']['foreign_id'] = $user['User']['id'];
             $admin_data['Transaction']['class'] = 'User';
             $admin_data['Transaction']['user_id'] = ConstUserIds::Admin;
             $admin_data['Transaction']['amount'] = $paymentDetails['paymentInfoList.paymentInfo(0).receiver.amount'];
             $admin_data['Transaction']['payment_gateway_id'] = ConstPaymentGateways::PayPal;
             $admin_data['Transaction']['transaction_type_id'] = ConstTransactionTypes::User;
             $this->User->Transaction->create();
              $this->User->Transaction->save($admin_data);
            }
            $this->User->Transaction->create();
                $_Data['User']['is_active'] = (Configure::read('user.is_admin_activate_after_register')) ? 0 : 1;
                $_Data['User']['is_paid'] = 1;
                $_Data['User']['id'] = $user['User']['id'];
                $this->User->save($_Data);
        }
        $this->_savePaidLog($user_id, $paymentDetails, 'User', 1);
    }

  function processOrder($data)
    {
        // import project models
        App::import('Model', 'Project');
        $this->Project = new Project();
        // import user models
        App::import('Model', 'User');
        $this->User = new User();
        // Include paypal related files from vendor
        App::import('Vendor', 'adaptive_paypal/paypal_platform');
        $this->PaypalPlatform = new PaypalPlatform();
        $payment_gateway_id = ConstPaymentGateways::PayPal;
        if (!empty($data['payment_gateway_id'])) {
            $payment_gateway_id = $data['payment_gateway_id'];
        }
        // Toget fund details
        $projectfund = $this->Project->ProjectFund->find('first', array(
            'conditions' => array(
                'ProjectFund.id' => $data['item_id']
            ) ,
            'contain' => array(
                'Project' => array(
                    'User' => array(
                        'UserProfile' => array()
                    )
                ) ,
            ) ,
            'recursive' => 3
        ));
        if (empty($projectfund)) {
            $this->cakeError('error404');
        }
        $order_id = $data['item_id'];
        $ProjectFund['id'] = $projectfund['ProjectFund']['id'];
        if ($payment_gateway_id == ConstPaymentGateways::PayPal) {
            // Request specific required fields
            $PaypalPlatform = $this->_getPaypalPlatformObject();
            $currencyCode = Configure::read('site.currency_code');
            $startingDate = date('c');
            $endingDate = date('c', strtotime('+1 year'));
            $maxTotalAmountOfAllPayments = $projectfund['ProjectFund']['amount']; //pledge
            $senderEmail = "";
            $maxNumberOfPayments = "1";
            $paymentPeriod = "";
            $dateOfMonth = "";
            $dayOfWeek = "";
            $maxAmountPerPayment = "";
            $maxNumberOfPaymentsPerPeriod = "";
            $pinType = "";
            $cancelUrl = Router::url('/', true) . 'payments/cancel_order/project/' . $order_id;
            $returnUrl = Router::url('/', true) . 'payments/success_order/project/' . $order_id;
            $ipnNotificationUrl = Router::url('/', true) . 'payments/processpayment/project/' . $order_id.'/'.ConstResponseFrom::paypal;
            $resArray = $PaypalPlatform->CallPreapproval($returnUrl, $cancelUrl, $currencyCode, $startingDate, $endingDate, $maxTotalAmountOfAllPayments, $senderEmail, $maxNumberOfPayments, $paymentPeriod, $dateOfMonth, $dayOfWeek, $maxAmountPerPayment, $maxNumberOfPaymentsPerPeriod, $pinType, $ipnNotificationUrl);
            $ack = strtoupper($resArray["responseEnvelope.ack"]);
            if ($ack == "SUCCESS") {
                // tosave pre approval key in funds table starts
                $this->CustomizePaymentPage($resArray["preapprovalKey"]);
                $this->Project->ProjectFund->Behaviors->detach('Logable');
                $ProjectFund['project_id'] = $projectfund['ProjectFund']['project_id'];
                $ProjectFund['user_id'] = $projectfund['ProjectFund']['user_id'];
                $ProjectFund['pay_key'] = $resArray["preapprovalKey"];
                $this->Project->ProjectFund->save($ProjectFund, false);
                // tosave pre approval key in funds table ends
                $cmd = "cmd=_ap-preapproval&preapprovalkey=" . urldecode($resArray["preapprovalKey"]);
                $PaypalPlatform->RedirectToPayPal($cmd);
            } else {
                //Display a user friendly Error on the page using any of the following error information returned by PayPal
                //TODO - There can be more than 1 error, so check for "error(1).errorId", then "error(2).errorId", and so on until you find no more errors.
                $ErrorCode = urldecode($resArray["error(0).errorId"]);
                $ErrorMsg = urldecode($resArray["error(0).message"]);
                $ErrorDomain = urldecode($resArray["error(0).domain"]);
                $ErrorSeverity = urldecode($resArray["error(0).severity"]);
                $ErrorCategory = urldecode($resArray["error(0).category"]);
                $return['error_message'] = $ErrorMsg;
                $return['error'] = 1;
            }
        } else if ($payment_gateway_id == ConstPaymentGateways::Wallet) {
            $this->processOrderPayment($order_id, ConstPaymentGateways::Wallet);
        }
        $return['order_id'] = $order_id;
        return $return;
    }


    function processOrderPayment($order_id, $gateway_id = ConstPaymentGateways::PayPal, $is_from_paypal = ConstResponseFrom::site)
    {
        // note: Here post back check for ipn is not done as in adaptive payment the urls are not exposed.
        $this->_saveIPNLog();
        App::import('Model', 'Project');
        $this->Project = new Project();
        App::import('Model', 'EmailTemplate');
        $this->EmailTemplate = new EmailTemplate();
        App::import('Core', 'ComponentCollection');
        $collection = new ComponentCollection();
        App::import('Component', 'OauthConsumer');
        $this->OauthConsumer = new OauthConsumerComponent($collection);
        $projectFund = $this->Project->ProjectFund->find('first', array(
            'conditions' => array(
                'ProjectFund.id' => $order_id
            ) ,
            'contain' => array(
                'User' => array(
                    'fields' => array(
                        'User.id',
                        'User.username',
                        'User.available_wallet_amount',
                        'User.blocked_amount',
                        'User.email',
                        'User.fb_user_id',
                        'User.twitter_access_token',
                        'User.twitter_access_key',
                        'User.fb_access_token',
                        'User.fb_user_id',
                    ) ,
                ) ,'Project' => array(
                    'fields' => array(
                        'Project.id',
                        'Project.user_id'
                    ) ,
                ) ,
            ) ,
            'recursive' => 2
        ));
        if (empty($projectFund)) {
            $this->cakeError('error404');
        }
        $project_id = $projectFund['ProjectFund']['project_id'];
        $_dataProjectFund['ProjectFund']['id'] = $projectFund['ProjectFund']['id'];
        if ($gateway_id == ConstPaymentGateways::PayPal) {
            $paymentDetails = $this->getPreapprovalDetails($projectFund['ProjectFund']['pay_key']);
            $paymentDetails['payKey'] = $projectFund['ProjectFund']['pay_key'];
            if ($paymentDetails['approved'] == 'true') {
                //$this->_savePaidLog($order_id, $paymentDetails, 'ProjectFund', 1);
                // if backer cancels pre-approval or owner refunds through paypal
                if (($paymentDetails['status'] == 'CANCELED' and !$projectFund['ProjectFund']['is_refunded']) || ($paymentDetails['status'] == 'REFUNDED' and !$projectFund['ProjectFund']['is_refunded'])) {
                    $this->refundProjectFund($order_id, ConstResponseFrom::paypal);
                }
            } else {
                $_dataProjectFund['ProjectFund']['is_failed'] = 1;
            }
        } else if ($gateway_id == ConstPaymentGateways::Wallet) {
            $blocked_user_balance = $projectFund['User']['blocked_amount']+$projectFund['ProjectFund']['amount'];
            $available_user_balance = $projectFund['User']['available_wallet_amount']-$projectFund['ProjectFund']['amount'];
            $this->Project->User->updateAll(array(
                'User.blocked_amount' => "'" . $blocked_user_balance . "'",
                'User.available_wallet_amount' => "'" . $available_user_balance . "'"
            ) , array(
                'User.id' => $projectFund['ProjectFund']['user_id']
            ));
        }
        $projectFundData = $this->Project->ProjectFund->find('first', array(
            'conditions' => array(
                'ProjectFund.id' => $_dataProjectFund['ProjectFund']['id']
            ) ,
            'recursive' => -1
        ));
        if (is_null($projectFundData['ProjectFund']['is_paid'])) {
            $this->log('Start transaction details');
            $data['Transaction']['user_id'] = $projectFund['ProjectFund']['user_id'];
            $data['Transaction']['foreign_id'] = $projectFund['ProjectFund']['id'];
            $data['Transaction']['class'] = 'ProjectFund';
            $data['Transaction']['amount'] = $projectFund['ProjectFund']['amount'];
            $data['Transaction']['site_commission'] = $projectFund['ProjectFund']['site_fee'];
            $data['Transaction']['payment_gateway_id'] = $gateway_id;
            $data['Transaction']['description'] = 'Payment Success';
            $data['Transaction']['transaction_type_id'] = ConstTransactionTypes::ProjectFunding;
            $owner_data['Transaction']['user_id'] = $projectFund['Project']['user_id'];
            $owner_data['Transaction']['foreign_id'] = $projectFund['ProjectFund']['id'];
            $owner_data['Transaction']['class'] = 'ProjectFund';
            $owner_data['Transaction']['amount'] = $projectFund['ProjectFund']['amount'];
            $owner_data['Transaction']['site_commission'] = $projectFund['ProjectFund']['site_fee'];
            $owner_data['Transaction']['payment_gateway_id'] = $gateway_id;
            $owner_data['Transaction']['description'] = 'Payment Success';
            $owner_data['Transaction']['transaction_type_id'] = ConstTransactionTypes::AmountFundedToOwner;

            $this->Project->User->Transaction->log($data);
            $transaction_id = $this->Project->User->Transaction->id;
            $this->Project->User->Transaction->log($owner_data);

            $admin_data['Transaction']['user_id'] = ConstUserIds::Admin;
            $admin_data['Transaction']['foreign_id'] = $projectFund['ProjectFund']['id'];
            $admin_data['Transaction']['class'] = 'ProjectFund';
            $admin_data['Transaction']['amount'] = $projectFund['ProjectFund']['site_fee'];
            $admin_data['Transaction']['site_commission'] = $projectFund['ProjectFund']['site_fee'];
            $admin_data['Transaction']['payment_gateway_id'] = $gateway_id;
            $admin_data['Transaction']['description'] = 'Payment Success';
            $admin_data['Transaction']['transaction_type_id'] = ConstTransactionTypes::AmountFundedToOwner;
            $this->Project->User->Transaction->log($admin_data);
            $this->log('Transaction logged.');
            $this->Project->ProjectFund->updateAll(array(
                'ProjectFund.is_paid' => '0',
                'ProjectFund.payment_gateway_id' => $gateway_id,
                'ProjectFund.is_canceled_from_paypal' => $is_from_paypal,
            ) , array(
                'ProjectFund.id' => $_dataProjectFund['ProjectFund']['id']
            ));
            $this->log('Project fund updated.');
            $project = $this->Project->find('first', array(
                'conditions' => array(
                    'Project.id' => $projectFund['ProjectFund']['project_id']
                ) ,
                'contain' => array(
                    'User' => array(
                        'fields' => array(
                            'User.id',
                            'User.username',
                            'User.email'
                        ) ,
                        'ProjectFund' => array(
                            'fields' => array(
                                'ProjectFund.user_id',
                                'ProjectFund.amount',
                                'ProjectFund.is_failed'
                            )
                        ) ,
                        'ProjectFollower' => array(
                            'fields' => array(
                                'ProjectFollower.user_id'
                            )
                        ) ,
                    ) ,
                    'Attachment',
                ) ,
                'fields' => array(
                    'Project.collected_amount',
                    'Project.needed_amount',
                    'Project.commission_amount',
                    'Project.reserve_amount',
                    'Project.user_id',
                    'Project.is_allow_over_funding',
                    'Project.name',
                    'Project.project_status_id',
                    'Project.slug',
                    'Project.short_description',
                    'Project.id'
                ) ,
                'recursive' => 2
            ));
            if($_dataProjectFund['ProjectFund']['is_failed'] == 0)
            {
            if (($project['Project']['collected_amount']+$projectFund['ProjectFund']['amount']) == $project['Project']['needed_amount'] && !($project['Project']['is_allow_over_funding'])) {
                $updates = array(
                    'Project.collected_amount' => 'Project.collected_amount + ' . $projectFund['ProjectFund']['amount'],
                    'Project.collected_percentage' => '(Project.collected_amount/Project.needed_amount)*100',
                    'Project.project_status_id' => ConstProjectStatus::FundingClosed,
                    'Project.project_fund_goal_reached_date' => "'" . date('Y-m-d H:i:s') . "'",
                );
                // sending Mail to owner
                $owner_user[] = $project['Project']['user_id'];
                $return_owner_lists = $this->Project->_sendAlertOnProjectSuccessful(array_unique($owner_user) , $project, ConstProjectUsers::Owner);
                // send mail to backed
                $pledged_users = Set::extract('/ProjectFund/user_id', $project);
                $pledged_user_lists = $this->Project->_sendAlertOnProjectSuccessful(array_unique($pledged_users) , $project, ConstProjectUsers::Backer, $return_owner_lists);
                // send mail to followers
                $follow_users = Set::extract('/ProjectFollower/user_id', $project);
                $this->Project->_sendAlertOnProjectSuccessful(array_unique($follow_users) , $project, ConstProjectUsers::Follower, $pledged_user_lists);
                // Send mail to admin
                $this->Project->_sendAlertOnProjectStatusToAdmin($project, $project['Project']['project_status_id'], ConstProjectStatus::FundingClosed);
                $this->Project->_executepay($project['Project']['id']);
            } elseif ($project['Project']['collected_amount']+$projectFund['ProjectFund']['amount'] >= $project['Project']['needed_amount']) {
                $updates = array(
                    'Project.collected_amount' => 'Project.collected_amount + ' . $projectFund['ProjectFund']['amount'],
                    'Project.collected_percentage' => '(Project.collected_amount/Project.needed_amount)*100',
                );
                if (($project['Project']['project_status_id'] == ConstProjectStatus::OpenForFunding || $project['Project']['project_status_id'] == ConstProjectStatus::ReserveAmountReached) && $project['Project']['project_status_id'] != ConstProjectStatus::GoalReached) {
                    $updates['Project.project_fund_goal_reached_date'] = "'" . date('Y-m-d H:i:s') . "'";
                    $updates['Project.project_status_id'] = ConstProjectStatus::GoalReached;
                    // sending Mail to owner
                    $owner_user[] = $project['Project']['user_id'];
                    $return_owner_lists = $this->Project->_sendAlertOnProjectGoalReached(array_unique($owner_user) , $project, ConstProjectUsers::Owner);
                    // send mail to backed
                    $pledged_users = Set::extract('/ProjectFund/user_id', $project);
                    $pledged_user_lists = $this->Project->_sendAlertOnProjectGoalReached(array_unique($pledged_users) , $project, ConstProjectUsers::Backer, $return_owner_lists);
                    // send mail to followers
                    $follow_users = Set::extract('/ProjectFollower/user_id', $project);
                    $this->Project->_sendAlertOnProjectGoalReached(array_unique($follow_users) , $project, ConstProjectUsers::Follower, $pledged_user_lists);
                    // Send mail to admin
                    $this->Project->_sendAlertOnProjectStatusToAdmin($project, $project['Project']['project_status_id'], ConstProjectStatus::GoalReached);
					$this->Project->_executepay($project['Project']['id']);
                } elseif ($project['Project']['project_status_id'] == ConstProjectStatus::GoalReached) {
                    $this->Project->_executepay($project['Project']['id']);
                }
            } elseif (!empty($project['Project']['reserve_amount']) && $project['Project']['collected_amount']+$projectFund['ProjectFund']['amount'] >= $project['Project']['reserve_amount'] && $projectFund['ProjectFund']['is_failed'] == 0) {
                $updates = array(
                    'Project.collected_amount' => 'Project.collected_amount + ' . $projectFund['ProjectFund']['amount'],
                    'Project.collected_percentage' => '(Project.collected_amount/Project.needed_amount)*100',
                );
                if ($project['Project']['project_status_id'] == ConstProjectStatus::ReserveAmountReached) {
                    $this->Project->_executepay($project['Project']['id']);
                }
                if ($project['Project']['project_status_id'] == ConstProjectStatus::OpenForFunding && $project['Project']['project_status_id'] != ConstProjectStatus::GoalReached && $project['Project']['project_status_id'] != ConstProjectStatus::ReserveAmountReached) {
                    $updates['Project.reserve_reached_date'] = "'" . date('Y-m-d H:i:s') . "'";
                    $updates['Project.project_status_id'] = ConstProjectStatus::ReserveAmountReached;
                    // sending Mail to owner
                    $owner_user[] = $project['Project']['user_id'];
                    $return_owner_lists = $this->Project->_sendAlertOnProjectReserveAmountReached(array_unique($owner_user) , $project, ConstProjectUsers::Owner);
                    // send mail to backed
                    $pledged_users = Set::extract('/ProjectFund/user_id', $project);
                    $pledged_user_lists = $this->Project->_sendAlertOnProjectReserveAmountReached(array_unique($pledged_users) , $project, ConstProjectUsers::Backer, $return_owner_lists);
                    // send mail to followers
                    $follow_users = Set::extract('/ProjectFollower/user_id', $project);
                    $this->Project->_sendAlertOnProjectReserveAmountReached(array_unique($follow_users) , $project, ConstProjectUsers::Follower, $pledged_user_lists);
                    // Send mail to admin
                    $this->Project->_sendAlertOnProjectStatusToAdmin($project, $project['Project']['project_status_id'], ConstProjectStatus::ReserveAmountReached);
                    $this->Project->_executepay($project['Project']['id']);
                }
            } else {
                $updates = array(
                    'Project.collected_amount' => 'Project.collected_amount + ' . $projectFund['ProjectFund']['amount'],
                    'Project.collected_percentage' => '(Project.collected_amount/Project.needed_amount)*100',
                );
            }
         }
            $user_preference = $this->Project->_getPermissionPerference($project['Project']['user_id']);
            if ($user_preference['UserPermissionPreference']['new_fund_notification_mail'] == 1) {
                $this->Project->_sendAlertOnProjectStatus($project, 'New fund notification', $projectFund);
            }
            $user_preference_backer = $this->Project->_getPermissionPerference($projectFund['ProjectFund']['user_id']);
            if ($user_preference_backer['UserPermissionPreference']['new_fund_backer_notification_mail'] == 1) {
                $this->Project->_sendAlertOnProjectStatus($project, 'New fund buyer notification', $projectFund, 'buyer');
            }
            $updates['Project.commission_amount'] = '"' . ($project['Project']['commission_amount']+$projectFund['ProjectFund']['site_fee']) . '"';
            $this->Project->_sendAlertOnProjectStatus($project, 'New fund notification', $projectFund, 'admin');
            $this->Project->Behaviors->detach('Logable');
            $this->Project->updateAll($updates, array(
                'Project.id' => $projectFund['ProjectFund']['project_id']
            ));
            $user = $this->Project->User->UserPermissionPreference->find('first', array(
                'conditions' => array(
                    'UserPermissionPreference.user_id' => $projectFund['ProjectFund']['user_id']
                ) ,
                'recursive' => -1
            ));
            if ($user['UserPermissionPreference']['fb_status_project_pledged']) {
                if ($projectFund['User']['fb_user_id'] > 0) {
                    $fb_message = $projectFund['User']['username'] . ' ' . __l('pledged for ') . ' "' . $project['Project']['name'] . '" in' . ' ' . Configure::read('site.name');
                    $getFBReturn = $this->postOnFacebook($project, $fb_message, 0, $projectFund);
                }
            }
            // post on user twitter
            if ($user['UserPermissionPreference']['twitter_status_new_project']) {
                if (!empty($projectFund['User']['twitter_access_token']) && !empty($projectFund['User']['twitter_access_key'])) {
                    $message = $projectFund['User']['username'] . ' ' . __l('pledged for ') . ' "' . $project['Project']['name'] . '" in' . ' ' . Configure::read('site.name');
                    $xml = $this->OauthConsumer->post('Twitter', $projectFund['User']['twitter_access_token'], $projectFund['User']['twitter_access_key'], 'https://twitter.com/statuses/update.xml', array(
                        'status' => $message
                    ));
                }
            }
            $_dataProjectFund['ProjectFund']['coupon_code'] = $this->_uuid();
            $_dataProjectFund['ProjectFund']['unique_coupon_code'] = $this->_unum();
        }
        $this->Project->ProjectFund->Behaviors->detach('Logable');
        $_dataProjectFund['ProjectFund']['user_id'] = $projectFund['ProjectFund']['user_id'];
        $_dataProjectFund['ProjectFund']['project_id'] = $project_id;
        $this->Project->ProjectFund->save($_dataProjectFund, false);
    }

    function executeProjectFund($order_id)
    {
        
        App::import('Model', 'Project');
        $this->Project = new Project();
        App::import('Vendor', 'adaptive_paypal/paypal_platform');
        $this->PaypalPlatform = new PaypalPlatform();
        $projectFund = $this->Project->ProjectFund->find('first', array(
            'conditions' => array(
                'ProjectFund.id' => $order_id,
            ) ,
            'contain' => array(
                'User',
                'Project' => array('User' => array('UserProfile')),
            ) ,
            'recursive' => 3,
        ));
        if (empty($projectFund)) {
            $this->cakeError('error404');
        }
        if ($projectFund['ProjectFund']['payment_gateway_id'] == ConstPaymentGateways::PayPal) {
            $itemDetail['payKey'] = $projectFund['ProjectFund']['pay_key'];
            // code for delayed chained payment starts
            $paymentGateway = $this->Project->User->Transaction->PaymentGateway->find('first', array(
                'conditions' => array(
                    'PaymentGateway.id' => $projectFund['ProjectFund']['payment_gateway_id'],
                ) ,
                'contain' => array(
                    'PaymentGatewaySetting' => array(
                        'fields' => array(
                            'PaymentGatewaySetting.key',
                            'PaymentGatewaySetting.test_mode_value',
                            'PaymentGatewaySetting.live_mode_value',
                        ) ,
                    ) ,
                ) ,
                'recursive' => 1
            ));
            $gateway_fee = 0;
            // project owner paypal account
            if (!empty($paymentGateway['PaymentGatewaySetting'])) {
                foreach($paymentGateway['PaymentGatewaySetting'] as $paymentGatewaySetting) {
                    $gateway_settings_options[$paymentGatewaySetting['key']] = $paymentGateway['PaymentGateway']['is_test_mode'] ? $paymentGatewaySetting['test_mode_value'] : $paymentGatewaySetting['live_mode_value'];
                }
            }
            $gateway_settings_options['is_test_mode'] = $paymentGateway['PaymentGateway']['is_test_mode'];
            $this->PaypalPlatform->settings($gateway_settings_options);
            // Request specific required fields
            $actionType = "PAY";
            $cancelUrl = Router::url('/', true) . 'payments/cancel_order/project/' . $order_id;
            $returnUrl = Router::url('/', true) . 'payments/success_order/project/' . $order_id;
            $ipnNotificationUrl = Router::url('/', true) . 'payments/processpayment/project/' . $order_id;
            $currencyCode = Configure::read('site.currency_code');
            $receiverEmailArray = array(
                $gateway_settings_options['payee_account'], $projectFund['Project']['User']['UserProfile']['paypal_account']
            );
            $receiverAmountArray = array(
                $projectFund['ProjectFund']['site_fee'], $projectFund['ProjectFund']['amount']
            );
            $receiverPrimaryArray = array('', true);
            $receiverInvoiceIdArray = array(
                md5('pledge_' . date('YmdHis'))
            );
            $senderEmail = '';
            $feesPayer = $this->_gatewayFeeSettings();
            $memo = '';
            $pin = '';
            $preapprovalKey = $projectFund['ProjectFund']['pay_key'];
            $reverseAllParallelPaymentsOnError = '';
            $trackingId = $this->PaypalPlatform->generateTrackingID();
            // Make the Pay API call
            $resArray = $this->PaypalPlatform->CallPay($actionType, $cancelUrl, $returnUrl, $currencyCode, $receiverEmailArray, $receiverAmountArray, $receiverPrimaryArray, $receiverInvoiceIdArray, $feesPayer, $ipnNotificationUrl, $memo, $pin, $preapprovalKey, $reverseAllParallelPaymentsOnError, $senderEmail, $trackingId);
            $ack = strtoupper($resArray["responseEnvelope.ack"]);
            // code for delayed chained payment ends
            if ($ack == "SUCCESS") {
                $return['error'] = 0;
                if (($resArray['paymentExecStatus']) == 'COMPLETED') {
                    $return['error'] = 0;
                    $this->log('Payment completed.');
                    $_projectFundData['id'] = $projectFund['ProjectFund']['id'];
                    $_projectFundData['is_paid'] = 1;
                    $_projectFundData['user_id'] = $projectFund['ProjectFund']['user_id'];
                    $_projectFundData['project_id'] = $projectFund['ProjectFund']['project_id'];
                    $this->Project->Behaviors->detach('Logable');
                    $this->log('Project fund updated.');
                    $this->Project->ProjectFund->save($_projectFundData, false);
                } else {
                    $return['error'] = 1;
                }
            } else {
                $return['error'] = 1;
            }
        } else if ($projectFund['ProjectFund']['payment_gateway_id'] == ConstPaymentGateways::Wallet) {
            $update_user_balance = $projectFund['User']['blocked_amount']-$projectFund['ProjectFund']['amount'];
            //update funder user
			if ($projectFund['ProjectFund']['payment_gateway_id'] == ConstPaymentGateways::Wallet) {
				$this->Project->User->updateAll(array(
					'User.blocked_amount' => "'" . $update_user_balance . "'",
				) , array(
					'User.id' => $projectFund['ProjectFund']['user_id']
				));
			}
            $user_info = $this->Project->User->find('first', array(
                'conditions' => array(
                    'User.id' => $projectFund['Project']['user_id']
                ) ,
                'fields' => array(
                    'User.id',
                    'User.username',
                    'User.available_balance_amount',
                    'User.available_wallet_amount',
                ) ,
                'recursive' => -1
            ));
            $update_project_owner_balance = $user_info['User']['available_wallet_amount']+$projectFund['ProjectFund']['amount']-$projectFund['ProjectFund']['site_fee'];
            //update project owner
            $this->Project->User->updateAll(array(
                'User.available_wallet_amount' => "'" . $update_project_owner_balance . "'",
            ) , array(
                'User.id' => $projectFund['Project']['user_id']
            ));
            $return['error'] = 0;
            $_projectFundData['ProjectFund']['id'] = $order_id;
            $_projectFundData['ProjectFund']['is_paid'] = '1';
            $_projectFundData['ProjectFund']['user_id'] = $projectFund['ProjectFund']['user_id'];
            $_projectFundData['ProjectFund']['project_id'] = $projectFund['ProjectFund']['project_id'];
            $this->Project->Behaviors->detach('Logable');
            $this->Project->ProjectFund->save($_projectFundData, false);
        }
        return $return;
    }
    
    public function updateProjectFunds($project_funds_id, $payment_id, $transaction_status){
        if($transaction_status == 1){
            $status = 'Giao dịch mới tạo, chưa thanh toán';
        }
        else if($transaction_status == 2){
            $status = 'Đã thanh toán, đang bị tạm giữ';
        }
        else if($transaction_status == 3){
            $status = 'Giao dịch bị huỷ/hoàn trả';
        }
        else if($transaction_status == 4){
            $status = 'Giao dịch hoàn thành';
        }
        else {
            $status = 'Undefined';
        }
        $project_fund = $this->query('select is_paid, amount, project_id from project_funds where id = '.$project_funds_id);
        $project_fund = $project_fund[0]['project_funds'];
        $projectInfomation = $this->query('SELECT SUM(amount) `total_amount`,COUNT(id) `num_funds` FROM project_funds WHERE is_paid = 1 AND is_refunded = 0 AND project_id = '.$project_fund['project_id']);
        $projectInfomation = $projectInfomation[0][0];
        
        $payment_id = 'NL-'.$payment_id;
        $modified_at = date('Y-m-d h:i:s');
        if($project_fund['is_paid'] != 1){
            $query_update_status = "update project_funds set is_paid = 1, ";
            $query_update_status .= "pay_key = '".$payment_id."', ";
            $query_update_status .= "modified = '".$modified_at."', ";
            $query_update_status .= "payment_status = '".$status."' ";
            $query_update_status .= "where  id = ".$project_funds_id;
            
            $query_update_project = "update projects set collected_amount = ".$projectInfomation['total_amount'].", project_fund_count = ".$projectInfomation['num_funds'].", modified = '".$modified_at."' where  id = ".$project_fund['project_id'];
            $this->query($query_update_status);
            $this->query($query_update_project);
        }
    }
    
    public function updateRefund($list_pf_id, $isUnrefund = 0){
        if(!$list_pf_id){
            return false;
        }
        $project_id = '';
        foreach($list_pf_id as $project_funds_id){
            $project_fund = $this->query('select is_paid, amount, project_id, is_refunded from project_funds where id = '.$project_funds_id);
            $project_fund = $project_fund[0]['project_funds'];
            $project_id = $project_fund['project_id'];

            $modified_at = date('Y-m-d h:i:s');
            if($project_fund['is_paid'] == 1){
                if($project_fund['is_refunded'] == $isUnrefund){
                    // update refund status of project funds 
                    $query_update_status = "update project_funds set ";
                    $query_update_status .= "modified = '".$modified_at."', ";
                    if($isUnrefund == 1){
                        $query_update_status .= "is_refunded = 0 ";
                    }
                    else {
                        $query_update_status .= "is_refunded = 1 ";
                    }
                    $query_update_status .= "where id = ".$project_funds_id;

                    // update collect amount of project
                    $query_update_project = " update projects set ";
                    if($isUnrefund == 1){
                        $query_update_project .= " collected_amount = collected_amount + ".$project_fund['amount'];
                    }
                    else {
                        $query_update_project .= " collected_amount = collected_amount - ".$project_fund['amount'];
                    }
                    $query_update_project .= ", modified = '".$modified_at."' ";
                    $query_update_project .= " where  id = ".$project_fund['project_id'];

                    $this->query($query_update_status);
                    $this->query($query_update_project);
                }
            }
        }
        
        return $project_id;
    }
    
    public function updateProjectFee($project_id, $price){
        $query_update_project_fee = "update projects set fee_amount = '".$price."' where  id = ".$project_id;
        
        $this->query($query_update_project_fee);
    }
}
?>